Home > Blockchain >  Pass CSS variable as prop to the react component
Pass CSS variable as prop to the react component

Time:03-16

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']} />
  )
}

CodePudding user response:

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>

  • Related