Is using a variable to set an attribute better practice than using object properties to set attributes?

Question

Is using a variable to set an attribute better practice than using object properties to set attributes?

Answer

The decision to use a variable to set an attribute vs. using object properties to set attributes will depend on how many attributes with different values we would like to set - if we only need to set a single attribute value (or the same attribute value on multiple elements) we can easily use a variable, but if we need to set multiple attribute values, using object properties may be a better choice.

For example:

const myAttr = 'test'; // we can use a variable to set a single attribute value, or multiple of the same attribute value

const myElement = (
  <div>
    <h2 className={myAttr}>A New Heading</h2>
    <h2 className={myAttr}>Another Heading</h2>
    <h2 className={myAttr}>And Another Heading</h2>
  </div>
)
const myAttrObj = {
  attrOne: 'attrOne',
  attrTwo: 'attrTwo',
  attrThree: 'attrThree'
}; // we can use object properties to set multiple attribute values

const myJSXElement = (
  <nav>
    <span id={myAttrObj.attrOne}></span>
    <span id={myAttrObj.attrTwo}></span>
    <span id={myAttrObj.attrThree}></span>
  </nav>
 )
12 Likes

Sorry, but shouldn’t we use “className” attribute instead “class” in first example of JSX?

18 Likes

I noticed that, too!

1 Like

Oh my goodness, thanks for pointing this out. Fixing now!

10 Likes

Really wish the autograder would respect white space

4 Likes

Hey Aubrey, just wondering if you are perhaps the /one of the creators of this course? It’s excellent.

2 Likes

This is interesting. It’s about the first time I’m seeing a second comment/response from you after making the main post. :slight_smile: :smiley:

3 Likes