31

When using styled-components to style a custom functional react component, the styles are not being applied. Here is a simple example where the styles are not being applied to the StyledDiv:

const Div = () => (<div>test</div>)
const StyledDiv = styled(Div)`
  color: red;
`;

What is the best way to make sure that the styles get applied correctly?

4 Answers 4

68

From the docs:

The styled method works perfectly on all of your own or any third-party components as well, as long as they pass the className prop to their rendered sub-components, which should pass it too, and so on. Ultimately, the className must be passed down the line to an actual DOM node for the styling to take any effect.

For example, your component would become:

const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
  color: green;
`;

Modified example:

const styled = styled.default
const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
  color: green;
  font-size: larger;
`;
const App = () => {
  return(<StyledDiv>Test</StyledDiv>)
}

ReactDOM.render(<App />, document.querySelector('.app'))
<script src="//unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="//unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/3.4.9/styled-components.min.js"></script>
<div class="app"></div>

2
14

Using styled(Component) like that creates a class which is passed as a prop called className to the wrapped component.

You can then apply that to the root element:

const Div = ({ className }) => (
  <div className={className}>test</div>
)

const StyledDiv = styled(Div)`
  color: red;
`;
7

In case you cannot change the original component (it's imported or generated), let's assume that component is a <span>, you may wrap it with e.g. a <div> and nest the css rules, like so:

const ComponentICantTouchWrapper = ({className}) => (
    <div className={className}><ComponentICantTouch /></div>
);
const StyledComponentICantTouch = styled(ComponentICantTouchWrapper)`
    > span {
        color: red;
    }
`;
1
  • className is the trick, it works for me
    – chygo
    Commented Oct 22, 2023 at 8:07
1

In my case, I was trying to use styled components with material UI. The thought I had was to do this: (it worked in most cases)

const StyledTableRow = ({ className, children }) => (
    <TableRow className={className}>{children}</TableRow>
);

Not the answer you're looking for? Browse other questions tagged or ask your own question.