Home > Blockchain >  Reactjs problem with CSS variable in style prop
Reactjs problem with CSS variable in style prop

Time:12-15

Firstly, this is my code:

<div className="phone" style="--bg: var(--green)">

but the error like:

Error: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing 'em'}} when using JSX.

so I change my code into

<div className="phone" style={{--bg: var(--green)}}>
    <div className="name">So dien thoai</div>
</div>
<div className="fb" style={{--bg: var(--blue)}}>
    <div className="name">Facebook</div>
</div>
<div className="gg" style={{--bg: var(--red)}}>
    <div className="name">Google</div>
</div>

:root{
  --red: #ee4d2d;
  --blue: #0288d1;
  --green: #6cc942;
}
.phone, .fb, .gg{
    display: flex;
    padding: 4px 0;
    border: 1px solid black;
    background: var(--bg);
    
    .name{
        padding-left: 20px;
    }
}

They told me i can't use --bg in style={{ }}

CodePudding user response:

style={{'--bg': 'var(--green)'}}

in JSX you must use style attribute as above.

The first (outer) {} is the JSX syntax and the inner {} is the actual javascript object representing the style properties/values.

ReactDOM.render(<div style={{'--bg': 'var(--green)'}}/>, document.body)
body{ --green: green }

div{
  width: 200px;
  height: 100px;
  background: var(--bg); /* using the variable defined from JSX */
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>


I suggest you next time to Google the error instead of rushing to open a new question here, as there is a ton of information on Google

CodePudding user response:

example: style={{color: "var(--red)"}} not ";"
style={{ "--bg": "var(--red)", background: "var(--bg)" }}
demo: https://codesandbox.io/s/ecstatic-keldysh-4dspr?file=/src/App.js 
  • Related