Search code examples
javascriptcssreactjsstyled-componentsemotion

Can't pass props.style to "@emotion/styled" component


I'm using emotion styled components. I have a component called Layered which I define as follows:

import styled from "@emotion/styled";

interface LayeredProps {
    [key: string]: any
}

const Layered = (props: LayeredProps) => {

    return (
      <ComponentWrapper style={props.style}>
        <p>Hello</p>
        <p>World</p>
      </ComponentWrapper>
    )

};

export default Layered;

const ComponentWrapper = styled.div`
    display: flex;
    flex-direction: column;
`

In my main code, I create another component called <LayeredModified /> which is supposed to be Layered with some extra styling. The styling is:

const LayeredModified = styled(Layered)`
  margin-left: 20px !important;
  margin-right: 20px !important;
`

Layered itself is never explicitly rendered, only LayeredModified. However, when it renders, it does so without any margin adjustments. In other words, only the props defined within the Layered component are shown, and not those defined in LayeredModified. I tried printing props.style in Layered and it's always undefined.

I know I'm not passing an explicit style parameter, but I thought the point of Emotion Styles was that it passed whatever styles you defined for that component automatically. If explicit passing is needed, I'm not sure how to do so without completely redefining the style inline, which defeats the purpose of the const LayeredModified component.

What am I missing?


Solution

  • You're missing applying the passed styles to the component. You need to add a className prop to ComponentWrapper and then use the props.className in it to apply the passed styles.

    interface LayeredProps {
      className?: string,
      [key: string]: any
    }
    
    const Layered = (props : LayeredProps) => {
      return (
        <ComponentWrapper className={`${props.className}`}>
          <p>Hello</p>
          <p>World</p>
        </ComponentWrapper>
      );
    };