Set component details dynamically

I need to set the details of the components after they are stored in a variable, here is the pseudocode:

render(){ let items = [{title:'hello'}, {title:'world'}]; let component = false; switch (id) { case 1: component = <A /> break; case 2: component = <B /> break; } return( items.map((item, index)=>{ return( <span> {/* SOMETHING LIKE THIS WOULD BE COOL - IS THAT EVEN POSSIBLE*/} {component.props.set('title', item.title)} </span>11 ) }) ) } 

Inside return I run a loop where I need to set the details for the component that is stored inside the variable .... How to configure the details for this component that I saved earlier in the variable?

+5
source share
3 answers

The correct way is to use the React cloneElement method ( https://facebook.imtqy.com/react/docs/react-api.html#cloneelement ). You can achieve what you want:

 <span> { React.cloneElement( component, {title: item.title} ) } </span> 
+17
source

You can move the switch inside map() . Hope this helps!

 class A extends React.Component{ render(){ return <h1>Inside Component A:{this.props.title}</h1> } } class B extends React.Component{ render(){ return <h1>Inside Component B: {this.props.title}</h1> } } class Parent extends React.Component{ render(){ let items = [{title:'hello'}, {title:'world'}]; const finalItems = items.map((item, index) => { switch (parseInt(this.props.id)) { case 1: return <A title={item.title}/> case 2: return <B title={item.title}/> } }) return( <span> {finalItems} </span> ) } } ReactDOM.render(<div> <Parent id="1"/> <Parent id="2"/> <Parent id="3"/> </div>, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

You do not need to add the default case, since React will ignore undefined , which will be returned to map if the switch key fails.

0
source

This can be done by assigning not a jsx but a reference to the component, then use jsx in a loop using the component from the variable. Check out my code changes.

 render(){ let items = [{title:'hello'}, {title:'world'}]; let C = null; //null is more accurate for object variable switch (id) { case 1: C = A; //it is component reference, C must be from upper letter break; case 2: C = B; //it is component reference break; default: C = A; //good to have default for wrong ids } return( items.map((item, index)=>{ return( <span> <C {...item} /> //render component with props </span>11 ) }) ) } 

The most important things:

1. C=A; we set the value of the variable C for the target component

2. <C {...item} /> all properties of the object's object will be set in the child component.

3. It can be used in a standard way, for example: <C title={item.title} />

Some working examples: https://jsfiddle.net/maciejsikora/jtt91wL3/3/

0
source

Source: https://habr.com/ru/post/1258636/


All Articles