2

Firstly, this is my code:

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

But the error is 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={{ }}

0

2 Answers 2

5
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

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

1 Comment

I got it. Hao Wu was right, they needed inside "".
-2
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 

1 Comment

Putting all your text in a code block makes it really difficult to read. Can you please format it better?

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.