The journey of #100DaysOfCode (@Darine_Tleiss)

100daysofcode - Day66

Hello friends a new day is here, the 66th :face_with_hand_over_mouth: and our journey with react is rocking :star_struck:.

Yesterday we discussed the React conditionals.

Today we will dive more to work with the React lists. :innocent:

What is a React List ? :thinking:

  • 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.
  • To loop through the React list we mainly use the map , in JS

Example:

    function Car(props) {
      return <li>I am a { props.brand }</li>;
    }
    
    function Garage() {
      const cars = ['Ford', 'BMW', 'Audi'];
      return (
        <>
          <h1>Who lives in my garage?</h1>
          <ul>
            {cars.map((car) => <Car brand={car} />)}
          </ul>
        </>
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Garage />);

List keys :key:

  • A “key” is a special string attribute you need to include when creating lists of elements in React . Keys are used to React to identify which items in the list are changed, updated, or deleted.
  • Keys need to be unique to each sibling. But they can be duplicated globally.
  • The key should be a unique ID assigned to each item. As a last resort, you can use the array index as a key.

Example

    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>
        </>
      );
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Garage />);
4 Likes