Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  174] [ 1]  / answers: 1 / hits: 25974  / 6 Years ago, thu, september 27, 2018, 12:00:00

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?


More From » reactjs

 Answers
10

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>




[#53417] Friday, September 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deniseryannd

Total Points: 169
Total Questions: 85
Total Answers: 96

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;