The issue arises because both @emotion/core (used internally by Storybook) and styled-components define their own css prop, leading to a type conflict in TypeScript. When we import from Storybook, TypeScript tries to merge the types, causing the incompatibility.

Instead of using the css prop from styled-components directly, we can refactor our code to avoid the conflict altogether by using the styled API from styled-components. This approach is cleaner and sidesteps the need for additional type declarations.

Here’s a refactored version of our code that works seamlessly:

import React from "react";
import styled from "styled-components";
import { storiesOf } from "@storybook/react";

export default function App() {
 const H1 = styled.h1`
   background: red;
 `;
 return <H1>Hello world!</H1>;
}

output

  1. Avoiding the css Prop: By using the styled API instead of the css prop, we can eliminate the need to explicitly declare css as a prop for DOMAttributes. This avoids conflicts with @emotion/core.
  2. Scoped Styles: The styled API encapsulates styles within the component, making it easier to maintain and debug.

If we still need to use the css prop for certain use cases, we can explore options like:

  • Avoiding @emotion by ensuring Storybook doesn’t include conflicting packages in your project. This might involve configuring Storybook to avoid @emotion dependencies.
  • Using babel-plugin-styled-components to ensure proper css prop usage if we’re using css from styled-components.

Support On Demand!

ReactJS

Related Q&A