30

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?

jjbskir
  • 8,474
  • 9
  • 40
  • 53

4 Answers4

65

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/react@16.5.2/umd/react.development.js"></script>
<script src="//unpkg.com/react-dom@16.5.2/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>
Agney
  • 18,522
  • 7
  • 57
  • 75
  • Adding my codepen here as I tried to understand the problem before finding this answer. Now it works! Thanks. https://codepen.io/shnigi/pen/qBapQYB – Shnigi Dec 29 '20 at 13:25
  • 1
    Please update the link to docs: https://styled-components.com/docs/basics#styling-any-component – Satish Maurya Jan 04 '22 at 05:20
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;
`;
Steve Holgado
  • 11,508
  • 3
  • 24
  • 32
6

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;
    }
`;
Roy Shilkrot
  • 3,079
  • 29
  • 25
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>
);
ShaZam
  • 21
  • 3