javascript - Can one add React Keys after instantiation? -


i’m making collection of react elements , displaying them; follows trivial example frame problem of how-would-one-modify-an-preexisting-instantiated-element only.

var c = [   <div>a</div>,   <div>b</div>,   // ...   <div>z</div> ];  var listcomponents = react.createclass({     render: function() {         return <div>{c}</div>;     } });  reactdom.render(<listcomponents/>, document.getelementbyid('root')); 

while code above “works,” renders console message i’d rather not ignore:

warning: each child in array or iterator should have unique "key" prop. check render method of `listcomponents`. see https://fb.me/react-warning-keys more information.

superficially, add unique key="…" string each element in c , done it.

however, seems quite verbose, since have data in indexed array , functional language in theory can assign each key matching index value without manually having enter source literal.

i’d love able this...

c.foreach( (e,i) => e.key = );        // ...or call setter 

what’s *right* react-way -and- keep code clean?



addendum: ...for curious or want add key field...

the collection i'm using array of tuples containing meta-data , corresponding react element, custom component, or huge jsx block. example above overly trivializes actual data looks irregularities.

as source data quite long, updated often, , not maintained developer; highly error prone missed key fields or duplicates values manual entry. hence desire entirely programmatically. can not count on data owners properly. can't read code, ideally i'd rather not mess data structures lot of "programming goop."

the collection manipulated few times, putting various runs of elements other dynamically created wrappers, final collection generated few transformations, filters, , maps before displayed.

a major shout out wes bos, came clever solution works!

the code simple 1 liner , looking for:

c = c.map( (el,key) => react.cloneelement(el, {key} )); 

we're building new collection using .cloneelement() method, unaware of. needed, turns out.

in .map() operation, lambda function passed both element , index. it's return value cloned element, key property set.

by cleverly naming index element key, allows short notation expression { "key" : key }. object augments cloned object.

in end, end new collection of identical objects, each key property set index.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -