Instagram
youtube
Facebook
Twitter

Lists and Keys

Lists 

  • The list is used to display data in an ordered format and is traversed using the map() function.
  • lists are a continuous group of text or images.
import React from 'react'; 
  
function App(){
const myCity = ['Indore','Mumbai','Pune','Hyderabad'];   
const listItems = myCity.map((myCity)=>{   
    return <li>{myCity}</li>;   
});   
return(   
    <ul> {listItems} </ul> 
);
}  

export default App;

Output:

Indore
Mumbai
Pune
Hyderabad

Rendering List inside components

import React from 'react'; 
import ReactDOM from 'react-dom';   
function App(props) {
const numbers = props.numbers;
     
return (
<div>
<ul>
   {numbers.map((number) =>
    <li>{number}</li>
    )}
</ul>
</div>
);
}
const numbers = [1, 2, 3, 4, 5];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App numbers={numbers} />);

export default App;

Output:

1
2
3
4
5

Keys

  • Keys are used to identify which items have changed, are added, or are removed.
  • Keys should be given inside the array to give the elements a stable identity.
import React from 'react'; 
import ReactDOM from 'react-dom';   
function App(props) {
const numbers = props.numbers;
     
return (
<div>
<ul>
   {numbers.map((number) =>
    <li key={number.toString()}>{number}</li>
    )}
</ul>
</div>
);
}
const numbers = ['Indore', 'Mumbai', 'Pune', 'Hyderabad', 'Banglore'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App numbers={numbers} />);

export default App;

Output:

1 Indore
2 Mumbai
3 Pune
4 Hyderabad
5 Banglore