JSX add attribute to array of different objects

Viewed 193

I have a page with a bunch of sub-pages:

render(){
  let elements = [<Apple>,<Orange>,<Pear>];
  return <div>
    {Elements}
  </div>
}

I want to give each of these elements the same property, e.g. color:

render(){
  let elements = [<Apple>,<Orange>,<Pear>];
  elements.forEach(i=>i.setAttribute('color','blue')); //???
  return <div>
    {Elements}
  </div>
}

So that it would be equivalent to:

render(){
  return <div>
    <Apple color='blue'/>
    <Orange color='blue'/>
    <Pear color='blue'/>
  </div>
}

How would I do this?

2 Answers

Fix your elements to

let elements = [Apple, Orange, Pear];

then use array map to pass a common prop.

render() {
  let elements = [Apple, Orange, Pear];
  const elementsWithColorBlue = elements.map((Element) => (
    <Element color="blue" />
  ));
  
  return <div>{elementsWithColorBlue}</div>
}

An alternate way of writing than the answer above would be as below

render(){
  return (
    <div>
      {[Apple, Orange, Pear].map(Element => <Element color="blue" />)}
    </div>
  )
}
Related