

const getAnimalsContent = animals => animals.map(item => (ĩ9.99% of the time, I use the map function to render a list of items and, to be honest, I can’t recall any scenario in which I needed another loop. If you prefer, you can even use a function.


const renderAnimals = animals.map(item => ( However, if you would like, you can first use a variable to store results of the map and then render content of the variable. So far, we have used the map function directly in the return expression. Otherwise, it is ok to use an index for the key attribute. If it is not available, then create one for each item before the list is rendered. So, as the rule of thumb, if you have an array that can change, then use a unique id. Therefore, the list would not be re-rendered. If indexes are used as keys and we change the order of items, will React know about it? Well, it might not, as even though the order of items in an array changed, the keys did not. Imagine a scenario in which you have a list of items that can be reordered. Check it out!Īs I mentioned earlier, React uses the key attribute to track if there were any changes made. KendoReact is a professional UI component library on a mission to help you design & build business apps with React much faster. Using an index as a key in certain situations could lead us into a pitfall and cause bugs. Thanks to adding keys there are no more warnings in the console. Well, we could just use a loop index, couldn’t we? return ( The reason is that React uses these keys to track if items were changed, added, or removed. However, if you check the console log, you will see that there is a warning like, “Warning: Each child in a list should have a unique key prop.” Whenever you use a loop it is important to provide a unique key attribute. import React from ‘react’Ĭonst animals = You will rarely need a loop other than this one. The most common way of doing that is with the map function that will return JSX. When I first started with React, I realized quite early that I did not know how to loop through an array and render a list of items. You can read more about it on the React website. The above will be converted to something like this However, remember that JSX will not work directly in browsers and requires a build step to convert JSX markup into React.createElement function calls. It might remind you a bit of a templating language, but with JSX you can use the full power of JavaScript. JSX is a custom syntax extension to JavaScript which is used for creating markup with React. If you have worked with React before, then there is a high probability that you know what JSX is, or have at least heard of it. Wondering how to create loops in React? Learn about JSX and how to use methods like the map function to loop inside React JSX and render a list of items.
