Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom html attributes in JSX

There are different reasons behind it, but I wonder how to simply add custom attributes to an element in JSX?

like image 819
Andrey Borisko Avatar asked Jul 07 '15 15:07

Andrey Borisko


People also ask

How do you add HTML attribute in React?

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.

How do I create a custom attribute in HTML?

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.

Can you use custom HTML attributes?

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.

Are custom DOM attributes supported in React v16?

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.


1 Answers

EDIT: Updated to reflect React 16

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


Previous answer (React 15 and earlier)

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

like image 119
peterjmag Avatar answered Sep 23 '22 02:09

peterjmag