slopeofhope slopeofhope - 2 months ago 8
React JSX Question

where to format and map this array in the child component in ES6?

So I am getting a prop from a parent component. let's say that attribute has a data structure like the following: [{a: "a", b:"b"}, {c:"c", d:"d"}...]

And this is the component that gets this prop.

class Child extends Component {
constructore(props){
super();
this.state = {items: []}
// props.name {a: "a", b: "b"}
}
render(){
return(

)
}
}


Now before I render that in the child component I would like to map this into something else like

for (let key in names){
items.push(<MenuItem value={names[key]}
key={key} primaryText={names[key]} />);
}


the end result would be.

class Child extends Component {
constructore(props){
super();
this.state = {items: [<MenuItem value={"a"}>,
<MenuItem value{"b"},....etc
}
render(){
return(

)
}
}

Answer

You could do something like the following I'm modifying your array to be

[{key: "a", value:"b"}, {key:"c", value:"d"}...]

I hope this requisite is ok to change and would still apply to your challenge

class Child extends Component {
   constructor(props){
     super(props);
   }
   render(){
     return this.props.items.map((item)=> {
       return <MenuItem key={item.key} value={item.value}/>;
     })
   }
}

This is generally a good react pattern. Use it everywhere :)

Comments