Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set component's props dynamically

I need to set component's props after it is stored in a variable, here is pseudo code:

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 props for the component that is stored inside a variable.... How to set props for this component which I stored earlier in a variable?

like image 258
bukowski Avatar asked Oct 22 '16 13:10

bukowski


People also ask

How do I pass dynamic props in VUE JS?

To pass props dynamically to dynamic component in Vue. js, we can use the v-bind directive. in the template to pass all the properties in the currentProperties as props to the dynamic component component. We set the component to load by setting the is prop to the currentComponent` component name string.

Are Props reactive Vue?

Props and data are both reactiveWith Vue you don't need to think all that much about when the component will update itself and render new changes to the screen. This is because Vue is reactive.

How do you pass Props dynamically?

To pass props dynamically to dynamic component in Vue. js, we can check the current component being rendered in component and pass in the props accordingly. to check the value of currentComponent in the currentProps` computed property. And we return an object with the props we want to pass into the child component .


1 Answers

The proper way is to use React's cloneElement method (https://facebook.github.io/react/docs/react-api.html#cloneelement). You can achieve what you want by doing:

<span>   {     React.cloneElement(       component,       {title: item.title}     )   } </span> 
like image 85
Chara Plessa Avatar answered Sep 17 '22 00:09

Chara Plessa