Search code examples
reactjsstyled-components

Why is Styled Components Generating an Object?


I have some very basic code that uses Styled Components:

import styled from 'styled-components';

const Test = () => <div>foo</div>;
const StyledTest = styled(Test)`
  border: 10px solid red;
`;
console.log(typeof StyledTest); // object!!!

The problem is, that last console.log line logs object (NOT function), which of course causes an error when I try to use it.

This also happens when I try to style a component from a library:

import Modal from 'react-modal';
const StyledModal = styled(ReactModalAdapter)`
  border: 10px solid red;
`;
console.log(typeof StyledModal); // object!!!

What am I doing wrong?


Solution

  • The console.log of a styled-component element, will always be an object.

    For your code works correct you need to change the StyledTest, to:

    const StyledTest = styled.div`
      border: 10px solid red;
    `;
    

    and use this in Test:

    const Test = () => <StyledTest>foo</StyledTest>;
    
    

    First you need to styling and after apply what you are creating.

    To create like you did, the parameter you are passing in StyledTest, should be a style component, so if you have something like:

    const Test = styled(({ ...rest }) => <div {...rest} />)`
      border: 10px solid red;
    `;
    
    const StyledTest = styled(Test)`
      border: 10px solid blue;
    `;
    

    In that example, Test is a styled-component element, so you can edit this.