What is the cleanest way in React to add a variable name attribute?
The end result I want is: <div data-flag>Hello</div> where the name data-flag is stored in a const variable.
The ways I found now are:
const DATA_FLAG = 'data-flag';
const Hello = ({ name }) => {
const dataAttrs = { [DATA_FLAG]: true }
return <div {...dataAttrs}>Hello {name}</div>;
}
Or this one-line version (but I find it less readable):
const Hello = ({ name }) => <div {...{ [DATA_FLAG]: true }}>Hello {name}</div>;
You can play with it in this JSFiddle
These versions work fine if the attribute was variable (true or false) but in my case it's always true so I find it a bit over-killed and the syntax complex.
I would love to know if there is a cleaner way to achieve it.
I know that the best approach is to apply it directly like: <div data-flag>Hello</div> but I really need to store data-flag in a constant (as shared by other components).
const dataAttrs = { [DATA_FLAG]: '' }in your shared utility file, and then just extend it on the components you want to? Before React supported the object spread es6 syntax for attributes you had to doReact.DOM.div(syntax to get dynamic attributes.<div {...dataAttrs}>