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?
Styled Components allow you to style any custom component that you've created. First, the custom component must receive the prop className and pass it to the underlying DOM element. Once that is done, pass the custom component to the styled function and invoke it as a Tagged Template to receive a new Styled Component.
One way to dynamically change css properties with styled components is to insert a custom prop into your React component and access said property using the dollar sign and curly braces commonly used for template literals. Our current example is testing to see if our use pointer prop is true.
For simple, efficient, and uncomplicated styling, Emotion is a great CSS-to-JS library. On the other hand, for more unique and complex styling options, styled-components may be the better way to go.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With