In this article we will see how to iterate through a collection to render a list of elements in React. We will also have a look at how to fire callback from the children elements.
We will build a dynamic list of buttons with an ‘Add’ button to add a button to the list. A click on any of these buttons will log the position of the button in the list. Demo Here .
To create a list of elements using a for loop in React, create an empty array and push React elements directly into it. Then Render it like any other element:
Although it won’t be of any use in our app, React requires you to render a
key attribute with unique values. If you don’t do so, you will receive warnings in the JS console.
Let’s start with the function that will log the button index:
Then add the callback to each child button element by modifying the
render function above:
To pass our current
i value to each callback, use
.bind(null, i). The function.prototype.bind() function will create a new function with a global context (null used as context) and the current value of
i as the first argument (our
val parameter in the
Let’s start by abstracting the number of elements value in the state:
Follows the ‘Add’ button click callback:
Add the button element to our render method
And replace the
this.state.buttonNumber in the for loop:
This is it. Check out the demo here: https://jsbin.com/rakuya/edit?html,output
The example above is for explanation purposes. In production code, I would recommend the use of Array.prototype.map().
- With this method, you can pass an array of objects and elegantly access the children properties.
- Do not forget to pass the context (
this) as a second argument in
arr.map(callback[, thisArg]). Otherwise you won’t be able to access the child click callback function (
Thanks for reading !