2

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 2

1

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>
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>
  )
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.