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>
)