0

I have and array (JS) of data in React component. I want to generate dynamic divs using loop on that array.

One is it can be done with jquery / javascript

componentDidMount(){
    var headingsArray = //contains some data from backend;

    for (var i = 0; i < headingsArray.length; i++) {
        var maprow = '';
        maprow += "<div>"+ headingsArray[i] +"</div>";
       //Some More Data In maprow
       $('.parentDiv').append(maprow);
    }
}

render(){
   return(
       <div className="parentDiv"></div>
   )
}

What is the react way to do it? as i am new to react

1

1 Answer 1

5

Use array.map to it:

render() {
  const headingsArray = [] // data from your backend

  return (
    <div className="parentDiv">
      {headingsArray.map((heading, index) => <div key={index}>{heading}</div>)}
    </div>
  )
}

key is a very important prop when mapping through an array. With that, react know which elements have been added, changed or deleted.

In case you have any question regarding array.map, please check this link.

Sign up to request clarification or add additional context in comments.

7 Comments

What is (heading, index) here?
heading is the current element at index
Yes it did, now i am trying to implement it with 2d array. i am gonna accept this as an answer. thankyou :)
How do i map This Kind of Array
Object.keys(yourObject).map(key => console.log(key, yourObject[key]))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.