Reputation: 131
I have a React app. It is using styled components. In the main.css file, I have defined a variable like -
:root {
primaryColor: 'red';
}
In the React app, I have styled components like (not working) -
const myDiv = styled.div`
color: ${props => props.color? props.color : var(--primaryColor)};
`;
// Not working
If I use the styled component as (working) -
const myDiv = styled.div`
color: var(--primaryColor);
`;
It works.
How to make the first case work? which is to access the css variable inside the styled component.
Upvotes: 3
Views: 3636
Reputation: 191936
You are inside an expression that returns the content of props.color
or a string that includes the var
expression. Since it's a string you need to wrap it with quotes.
const MyDiv = styled.div`
color: ${props => props.color? props.color : 'var(--primaryColor)'};
`;
ReactDOM.render(
<MyDiv>Some text</MyDiv>,
root
);
:root {
--primaryColor: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.0/styled-components.js"></script>
<div id="root"></div>
Upvotes: 3