0

How to change data-reactid attributes to my custom attributes like data-hello="world" in react?

<a data-reactid="......" ></a>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 3
    Please show us your effort. What have you done so far. – Peter Mar 08 '16 at 12:42
  • Is this what you are trying to do? http://stackoverflow.com/q/31273093/74230 – Samuel Mar 08 '16 at 13:21
  • there is literally no reason to use data attributes in react. Whatever you're trying to achieve should be done other ways. – Blair Anderson Mar 17 '16 at 05:24
  • @BlairAnderson: `data-` attribs are great for hitting with CSS no matter the framework that makes the html – dandavis Mar 17 '16 at 07:53
  • @dandavis that is what classes are for? they are also framework agnostic. – Blair Anderson Mar 18 '16 at 17:29
  • @BlairAnderson: classes can be a lot harder to use when you're not hitting a "flag"-shaped value, like `[data-day=6]` or `[data-url$=.org]`... they are also used extensively by CSS frameworks like bootstrap and media embeds. I appreciate that _props_ should store "config", but with react's "hands-off" DOM restrictions, smarter CSS is more important than ever and can reduce JSX cruft. – dandavis Mar 18 '16 at 17:41
  • @dandavis yeah I think instead of using CSS to check `[data-url$=.org]` i would prefer to add classes or inline-styles in react. this video(https://youtu.be/RBg2_uQE4KM) was really enlightening to see how react will be able to help us eliminate excess css/styles in the future. – Blair Anderson Mar 18 '16 at 22:15

2 Answers2

8

Update: As of React 15, data-reactid has been removed and is never written to the DOM as an attribute

The short answer: Don't touch the data-reactid. Ever. It is a vital part of React, and basically used to perform the correct DOM manipulations when the virtual DOM tree is changed. Pretend it's not there.

However, you can add your own data- attributes in any way you wish:

render () {
    return (
        <h1 data-hello={this.props.hello}>{this.props.title}</h1>
    );
}

Working example: https://jsfiddle.net/0or98zjx/

dannyjolie
  • 10,959
  • 3
  • 33
  • 28
  • In your code still i can see

    A Title

    – nihar jyoti sarma Mar 15 '16 at 06:36
  • 1
    Of course, React injects data-reactid, as I said, because it is what React hooks into when the DOM changes. Just exactly what are you trying to do? If you want to manipulate data-reactid, you can pass `key="myId"` to the component. the output will be `

    `, but this is only necessary when iterating an array or something similar. See the updated fiddle: https://jsfiddle.net/0or98zjx/2/

    – dannyjolie Mar 15 '16 at 08:38
0

React creates the virtual DOM a, it measures the difference between the actual DOM and and virtual DOM if there is any change it will change the virtual DOM. So react.id will be a part of virtual DOM .

Kartikeya Sharma
  • 553
  • 1
  • 5
  • 22