ReactJs Tutorials
React List
Lists are used to display data in an ordered format and mainly used to display menus on websites. In React, Lists can be created in a similar way as we create lists in JavaScript.
The map() function is used for traversing the lists.
File name :
var numbers = [1, 2, 3, 4, 5];
const multiplyNums = numbers.map((number)=>{
return (number * 5);
});
console.log(multiplyNums);
Example
File name :
import React from 'react';
import ReactDOM from 'react-dom';
function Car(props) {
return <li>I am a { props.brand }</li>;
}
function Garage() {
const cars = ['Ford', 'BMW', 'Audi','Maruti'];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car brand={car} />)}
</ul>
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
File name :
import React from 'react';
import ReactDOM from 'react-dom';
const myList = ['Sata', 'Arham', 'Sana','Adiba'];
const listItems = myList.map((myList)=>{
return <li>{myList}</li>;
});
ReactDOM.render(
<ul> {listItems} </ul>,
document.getElementById('app')
);
export default App;
Keys
Keys allow React to keep track of elements. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list.
Keys need to be unique to each sibling. But they can be duplicated globally.
Generally, the key should be a unique ID assigned to each item.
File name :
import React from 'react';
import ReactDOM from 'react-dom';
function Car(props) {
return <li>I am a { props.brand }</li>;
}
function Garage() {
const cars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car key={car.id} brand={car.brand} />)}
</ul>
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
Rendering Lists inside components
File name : index.php
import React from 'react';
import ReactDOM from 'react-dom';
function NameList(props) {
const myLists = props.myLists;
const listItems = myLists.map((myList) =>
<li>{myList}</li>
);
return (
<div>
<h2>Rendering Lists inside component</h2>
<ul>{listItems}</ul>
</div>
);
}
const myLists = ['Sara', 'Arham', 'Sara', 'Areba', 'Adiba'];
ReactDOM.render(
<NameList myLists={myLists} />,
document.getElementById('app')
);
export default App;