For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

React for Beginners | Lists and Keys

Iterate over arrays in JSX using map

  • How do we displays lists in JSX using array data?
  • Use the .map() function to convert lists of data (arrays) into lists of elements,
const people = ["Junaid", "Aadil", "Musaddik"];
const peopleList = people.map((person) => <p>{person}</p>);
map() can be used for components as well as plain JSX elements.
function App() {
    const people = ["Junaid", "Aadil", "Musaddik"];

    return (
        <ul>
            {
                people.map((person) => {
                    <Person name={person} />
                })
            }
        </ul>
    );
}

function Person({name}) {
    // We access the 'name' prop directly using object destructuring 
    return <p>This person's name is : {name}</p>;
}

The importance of keys in lists

  • Each React element within a list of elements needs a special key prop
  • Keys are essential for React to be able to keep track of each element that is beeing iterated over with the .map() function
  • React uses keys to performantly update individual elements when their data changes (instead of re-rendering the entire list)
  • Keys need to have unique values to be able to identify each of them according to their key value
function App() {
	const people = [
		{ id : "Ksy7py", name : "Junaid" },
		{ id : "6eAdl9", name : "Aadil" },
		{ id : "6eAde9", name : "Musaddik" },
	];

	return (
		<ul>
			{
				people.map((person) => (
					<Person key={person.id} name={person.name} />
				))
			}
		</ul>
	);
}