ReactJs Lists
Syntax
The syntax for a basic React list component is as follows:
function List(props) {
const myList = props.items.map((item) => <li>{item}</li>);
return <ul>{myList}</ul>;
}
ReactDOM.render(<List items={['item1', 'item2', 'item3']} />, document.getElementById('root'));
Here, the List
function takes in props that contain an items
array. Using the map
method, each element of the items
array is mapped to an li
element, which is then returned in a ul
element.
Example
Consider the following code snippet:
function App() {
const items = ['ReactJs', 'Angular', 'Vue'];
return (
<div>
<h1>Programming Languages</h1>
<List items={items} />
</div>
);
}
function List(props) {
const myList = props.items.map((item) => <li>{item}</li>);
return <ul>{myList}</ul>;
}
ReactDOM.render(<App />, document.getElementById('root'));
This code renders a heading and a list of programming languages using the List
component.
Output
The output of the above example looks like the following:
Programming Languages
- ReactJs
- Angular
- Vue
Explanation
ReactJs provides a way to render lists using the map
method. The map
method maps each element of an array to a new element, as defined by a function provided as an argument.
In the above example, the List
function maps each element of the items
array to a new li
element, which is then returned in a ul
element. This list is then displayed in the App
component.
Use
ReactJs lists can be used to display any kind of data that is stored in an array. Lists can be used to render menus, blog posts, products, and more.
Important Points
- Lists must have a unique
key
attribute for each item in the list. - The
map
method is used to create a new array with the same number of elements as the original array. - The
map
method returns a new array and does not modify the original array.
Summary
ReactJs lists provide a simple and efficient way to render data that is stored in an array. The map
method is used to map each element of an array to a new element, which is then returned in a list. Lists must have a unique key
attribute for each item. Lists can be used to render menus, blog posts, products, and more.