5

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

2
  • object spread syntax seems like a completely fine solution. Why dont you put 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 do React.DOM.div( syntax to get dynamic attributes. Commented Sep 10, 2019 at 0:39
  • I think this is your best bet for that right now : <div {...dataAttrs}> Commented Sep 10, 2019 at 0:45

1 Answer 1

1

You could create a React element without using the JSX syntax. Something like this should work:

const DATA_FLAG = 'data-flag'

const Hello = ({ name }) => {
    const dataAttrs = { [DATA_FLAG]: true }
  return React.createElement('div', dataAttrs, `Hello ${name}`)
}

This only really makes the way you're passing in the attributes look easier on the eyes though. Don't think you'll get around defining a dataAttrs object for your props.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing this alternative. But yeah seems like I need to keep the dataAttrs no matter what.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.