Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-components not applying style to custom functional react component

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?

like image 780
jjbskir Avatar asked Sep 27 '18 18:09

jjbskir


People also ask

How do you style custom component styled-components?

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.

How can you apply dynamic styles to styled-components?

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.

Which is better Emotion or styled-components?

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.


1 Answers

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>
like image 192
Agney Avatar answered Sep 19 '22 16:09

Agney