Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: using object ref as {key}?

How can I use an object reference as {key} in ReactJS?

I've tried this:

let ruleList = _.map(this.state.rules, function(rule) {
      return <RuleList rule={rule} key={rule} />
    });

but this ends up being printed in the console:

Warning: flattenChildren(...): Encountered two children with the same key, .0:$[object Object]. Child keys must be unique; when two children share a key, only the first child will be used.

Any way to get around this without hacks such as generating IDs for each item?

like image 282
David Xu Avatar asked Jul 13 '15 22:07

David Xu


People also ask

How do you access the key of an object in React?

You just need to make use of the object name followed by the key name to access the key-value pair of the state object.

Can we pass key as props in React?

Keys Must Only Be Unique Among Siblings If you need the same value in your component, pass it explicitly as a prop with a different name: const content = posts.map((post) => <Post key={post.id} id={post.id} title={post.title} /> ); With the example above, the Post component can read props.id , but not props.key .

What is ref and key in React?

Refs is the shorthand used for references in React. It is similar to keys in React. It is an attribute which makes it possible to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it.

What is object key React?

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.


1 Answers

I had a similar situation where the object has no unique id.

I ended up generating ids for the items based on object references:

let curId = 1;
const ids = new WeakMap();

function getObjectId(object) {
  if (ids.has(object)) {
    return ids.get(object);
  } else {
    const id = String(curId++);
    ids.set(object, id);
    return id;
  }
}

// Usage
<RuleList rule={rule} key={getObjectId(rule)} />

I know you mentioned that you don't want to generate ids, but I thought I'd share this since it is generic and doesn't depend on any properties in your object.

like image 73
amann Avatar answered Oct 05 '22 22:10

amann