The above code will log the below output to the console:
[3, 4, 5, 6, 7]
Below code illustrate this:
The above code will render an unordered list as shown in below output:
Rendering lists inside Components
In the above code in React we had directly rendered the list to the DOM. But usually this not a good practice to render lists in React. We already have talked about the uses of Components and had seen that every thing in React is built as individual components. Consider the example of a Navigation Menu. It is obvious that in any webiste the items in a navigation menu are not hardcoded. This items are fetched from database and then displayed as lists in the browser. So from the component’s point of view we can say that we will pass a list to a component using props and then use this component to render the list to the DOM. We can update the above code in which we have directly rendered the list to now a component which will accept an array as props and returns an unordered list.
You can see in the above output that the unordered list is succefully rendered to the browser but a warning message is logged to the console.
Warning: Each child in an array or iterator should have a unique "key" prop
The above warning message says that each of the list items in our unordered list should have an unique key. A “key” is a special string attribute you need to include when creating lists of elements in React. We will dicuss about keys in details in further articles. For now, lets just assign a string key to each of our list items in the above code.
Below is the updated code with keys:
This code will give same output as that of the previous code but this time without any warning. Keys are used in React to identify which items in the list are changed, updated or deleted. In other words we can say that keys are used to give an indentity to the elements in the lists. We will learn about keys in more details in our next article.
- ReactJS | Introduction to JSX
- ReactJS | Props - Set 1
- ReactJS | Components
- ReactJS | forms
- ReactJS | Router
- ReactJS | Keys
- ReactJS | Components - Set 2
- ReactJS | Refs
- ReactJS | PropTypes
- ReactJS | Virtual DOM
- ReactJS | Props - Set 2
- Difference between ReactJS and Vue.js
- ReactJS | Fragments
- ReactJS | ReactDOM
- ReactJS | Using Babel
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.