There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?
To add custom HTML attributes in React, we can just add them as we do with regular HTML element attributes. We just add the custom-attribute custom attribute and it'll be rendered in the HTML. This works since React 16.
If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.
Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements.
With React 16, you can now pass custom attributes to all HTML and SVG elements, and React doesn't have to include the whole attribute allowlist in the production version. In other words, the way you use DOM components in React hasn't changed, but now you have some new capabilities.
Custom attributes are supported natively in React 16. This means that adding a custom attribute to an element is now as simple as adding it to a render
function, like so:
render() { return ( <div custom-attribute="some-value" /> ); }
For more:
https://reactjs.org/blog/2017/09/26/react-v16.0.html#support-for-custom-dom-attributes
https://facebook.github.io/react/blog/2017/09/08/dom-attributes-in-react-16.html
Custom attributes are currently not supported. See this open issue for more info: https://github.com/facebook/react/issues/140
As a workaround, you can do something like this in componentDidMount
:
componentDidMount: function() { var element = ReactDOM.findDOMNode(this.refs.test); element.setAttribute('custom-attribute', 'some value'); }
See https://jsfiddle.net/peterjmag/kysymow0/ for a working example. (Inspired by syranide's suggestion in this comment.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With