Correct way to inline style in JSX

Viewed 2656

I am trying to do inline style for which following is working

 <dt className='some-element' style={{backgroundColor : '#1a1a1a', fill: '#1a1a1a'}}>

Now I am trying to change the hex value every time so trying to have something like

let styleConfig = `backgroundColor : '${someColor}', fill: '${someColor}'`
<dt className='some-element' style={{styleConfig}}>

But I am not getting seeing style being applied as the first one nor I get any console error.

Any suggestion?

1 Answers

React components' attributes expect a value wrapped in quotes for strings or curly brackets (for other values and variables).

The 1st pair of curly brackets in style={{backgroundColor : '#1a1a1a', fill: '#1a1a1a'}} is the attribute value wrapper, and the 2nd is part of the object you pass as a value to the attribute - {backgroundColor : '#1a1a1a', fill: '#1a1a1a'}

Because of ES6 shorthand property names, this is what you actually get, when you pass the variable styleConfig into two pairs of curly brackets style={{styleConfig}}:

style={{ styleConfig: `backgroundColor : '${someColor}', fill: '${someColor}'` }}

In addition styleConfig should be an object, and not a string, because the style attribute expects an object of style properties.

Try this:

let styleConfig = { backgroundColor : 'red', fill: 'blue' } // create an object of style properties 
<dt className='some-element' style={styleConfig}> // use a single pair of curly brackets
Related