4

I am having this component that can be displayed in different colors depending on prop color that component received.

const Card = ({color}) => {
  return (
    <p style={{color}}>Some Text</p>
  )
}

I am having these global css variables:

:root{
    --bg-clr-1: #E7F8F8;
    --card-clr-red: #F03E3E;
    --card-clr-violet: #7950F2;
    --card-clr-green: #12B886;
    --text-clr: #333;
}

Is there a way to pass this css variable as prop to "Card" component? Like so:

import variableStyles from '../../styles/globalVariables.css'

const App = () => {
  return(
    <Card color={variableStyles['--text-clr']} />
  )
}

1 Answer 1

5

You can pass the variable string as a props, and inject that into var():

<p style={{ color: `var(${color})` }}>Some Text</p>

const Card = ({color}) => {
    return (
        <p style={{ color: `var(${color})` }}>Some Text</p>
    )
}

class Example extends React.Component {    
    render() {
        return (
            <React.Fragment>
                <Card color={'--card-clr-red'} />
                <Card color={'--card-clr-violet'} />
            </React.Fragment>
        );
    }
}

ReactDOM.render(<Example />, document.body);
:root{
    --bg-clr-1: #E7F8F8;
    --card-clr-red: #F03E3E;
    --card-clr-violet: #7950F2;
    --card-clr-green: #12B886;
    --text-clr: #333;
}
<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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.