Home > Software engineering >  Please explain this code in case react using key props when rendering all the list
Please explain this code in case react using key props when rendering all the list

Time:03-10

I'm currently learning react and I'm confused when reading this code.

Can someone explain to me what is going on in this code?

  const allItems = [
    {id: 'a', value: 'apple'},
    {id: 'o', value: 'orange'},
    {id: 'g', value: 'grape'},
    {id: 'p', value: 'pear'},
  ];

  function App() {
    const [items, setItems] = React.useState(allItems)

    function addItem() {
      setItems([...items, allItems.find(i => !items.includes(i))])
    }

    function removeItem(item) {
      setItems(items.filter(i => i !== item))
    };

    return (
      <div>
        <button disabled={items.length >= allItems.length} onClick={addItem}>
          add item
        </button>
        <ul style={{listStyle: 'none', paddingLeft: 0}}>
          {items.map(item => (
            <li key={item.id}>
              <button onClick={() => removeItem(item)}>remove</button>{' '}
              <label htmlFor={`${item.value}-input`}>{item.value}</label>{' '}
              <input id={`${item.value}-input`} defaultValue={item.value} />
            </li>
          ))}
        </ul>
      </div>
    )};

  ReactDOM.render(<App />, document.getElementById('root'));

I really appreciate it if you can explain to me in some easy to understand.

Thanks

CodePudding user response:

It is basically a component with two functions 1.) addItem and 2.) removeItem and it has an array of objects called allItems and a state called items.

so the first function addItem is used to add a single item into the state items and second function removeItem is used to remove a single item from the state items.

CodePudding user response:

When you render components from an array with .map(thing), you must manually assign a unique key property to each child that your map function returns.

The basic assumption is that your array of objects has some property which uniquely identifies each object, so you assign that property to each object.

Your example assumes that each item object has a unique id property to assign to the key prop.

Here are the docs.

  • Related