Skip to content
Advertisement

JSX template literals for an inline style

I’m trying to add an inline style on an element which includes variables.

Hard-coding the values works:

<circle style={{ strokeDasharray: "75, 25" }} ></circle>

But I need a way for both of the numbers in this style to pull from variables.

I’ve tried a variety of curly braces and backticks – I think I need template literals, but am not sure how the syntax works for them inside of the double curly braces that this inline style seems to require.

This one

<circle style={`{strokeDasharray: "${ percent }, 25"}`} ></circle>

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

This one

<circle style={{`strokeDasharray: "${ percent }, 25"`}} ></circle>

causes the build to fail completely.

This one

<circle style={{strokeDasharray: "`${ percent }`, 25"}} ></circle>

builds, but no inline style is added at all.

In addition to using the percent variable for the first numeric value, I need to calculate the second numeric value – it will always be 100 minus the percent variable.

Advertisement

Answer

The key thing here is that the code within the outer {} is pure JavaScript code (specifically, an expression [not a statement]). With the style property, you specify an object:

<circle style={yourObjectHere} />

In your case, you’re specifying an object literal, just like any other object literal in JavaScript. So you have the property name, a colon, and the property value. Since part of the value is from a variable, you use the usual ways of creating a concatenated string:

<circle style={{strokeDasharray: percent + ", 25"}} />

or

<circle style={{strokeDasharray: `${percent}, 25`}} />

etc.

(If you’re wondering why I used /> instead of ></circle>, it’s because even non-void elements are typically self-closed in JSX. JSX isn’t quite SVG or HTML or even XHTML, it’s its own beast.)


You probably want to calculate the second number as well, as Михаил Мишин shows, so with the above that’s:

<circle style={{strokeDasharray: percent + ", " + (100 - percent)}} />

or

<circle style={{strokeDasharray: `${percent}, ${100 - percent}`}} />
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement