styled-components not applying style to custom functional react component
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;
`;
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>
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;
}
`;