Taig
Taig

Reputation: 7288

Create unique id in getDefaultProps

In my component's getDefaultProps I'm returning an object like { id: idGenerator.unique() } which should give me a unique id on each method call. However, react does not execute the getDefaultProps() method per instance, but only once for the component. So I end up with the same not-so-unique id whenever I use the component.

Is there an alternative to hook the id into the props object of each instance?

Upvotes: 2

Views: 96

Answers (1)

WayneC
WayneC

Reputation: 5740

State from props is normally an antipattern, but may make sense here, eg:

var Foo = React.createClass({
   getInitialState: function() {
       return {
           id: this.props.id || idGenerator.unique()
       }
   }
   .....
});

And just use this.state.id instead of props. If the component is likely to get an ID at some point, you could handle that in componentWillReceiveProps

Upvotes: 3

Related Questions