Noitidart
Noitidart

Reputation: 37238

Non standard custom attributes in ReactJS?

This is regarding non-standard attributes. https://facebook.github.io/react/docs/tags-and-attributes.html

In react I have done this:

 React.createElement('div', {image:'blah', etc:'blah'});

I need image and etc to be set on the element with setAttribute, and I need react to use its smarts to maintain it as it changes.

A solution here https://stackoverflow.com/a/21654914/1828637 says to add it on componentDidMount but this is not a solution. The attribute will not be maintained as it changes by the react framework.

Is there anyway to tell react to set the attribute on my custom tags?

Upvotes: 3

Views: 5706

Answers (3)

Morris S
Morris S

Reputation: 2594

In react 16 custom attributes are now possible

// Your code:
<div mycustomattribute="something" />

// React 15 output:
<div /> 

// React 16 output:
<div mycustomattribute="something" />

react 16 custom attributes

Upvotes: 4

ohad serfaty
ohad serfaty

Reputation: 654

Another alternative is to change the name of the attribute to something that react supports (such as the data-* attributes) :

render() {
    return (
      <div data-image='blah' data-etc='blah' />
    );
}

link to other supported attributes: https://facebook.github.io/react/docs/dom-elements.html

Upvotes: 2

Eric O&#39;Connell
Eric O&#39;Connell

Reputation: 858

This solution is to build on the linked answer by using the React lifecycle method componentWillReceiveProps to update the DOM element attributes with every change to props. For more information about all the lifecycle methods, see http://facebook.github.io/react/docs/component-specs.html.

(Since componentWillReceiveProps can be called more often than when the props actually change, you may wish to compare the props before actually setting them on the node.)

I've provide fiddle you can play with: https://jsfiddle.net/p4h267bo/ and the relevant part of the code is excerpted here:

var Hello = React.createClass({
  componentDidMount() {
    this.mirrorProps(this.props);
  },
  componentWillReceiveProps(nextProps) {
    this.mirrorProps(nextProps);
  },
  mirrorProps(props) {
    var node = ReactDOM.findDOMNode(this);
    node.setAttribute('name', props.name);
  },
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

Upvotes: 2

Related Questions