Thursday, August 11, 2022

Using Inline Styles with React

Today I was adding an inline style to a React element and tried to set it from a string like this:
<div style={"background-image: url("+imgUrl+")"}>  </div>
Turns out that does not work. React requires that style attributes are set using objects. So the correct way to do this is:

<div> style={{backgroundImage: "url("+imgUrl+")"}}  </div>
After the equal sign the first open curly takes us into Javascript mode, and the second open curly is the beginning of an object literal. All style property names must be camelcase with no dashes.

Another thing I needed to do was conditionally add a class to an element based on a state variable. Here's how that turned out:

<h2> className={visible ? 'hilited' : ''} </h2>
The state variable is called "visible" and it's either true or false. When true I get the class of hilited, otherwise no class name.

Post a Comment

Note: Only a member of this blog may post a comment.