Computer scienceFrontendReactHooks

useReducer

Theory

Dynamic list

Report a typo

The below React component called DynamicList manages a dynamic list of items. Use useReducer to handle actions such as adding and removing items. The component should display the list and provide buttons to add and remove items. Fill in the gaps such that the code works as intended.

Fill in the gaps with the relevant elements
import React, {  } from 'react';

const listReducer = (state, action) => {
  switch (action.type) {
    case 'add':
      return [, action.item];
    case 'remove':
      return state.filter((item, index) => index !== );
    default:
      return state;
  }
};

const DynamicList = () => {
  const [list, dispatch] = useReducer(, []);

  const handleAddItem = () => {
    const newItem = `Item ${ + 1}`;
    dispatch({ type: 'add', item: newItem });
  };

  const handleRemoveItem = (index) => {
    dispatch({ type: 'remove', index });
  };

  return (
    <div>
      <ul>
        {list.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => handleRemoveItem(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={handleAddItem}>Add Item</button>
    </div>
  );
};

export default DynamicList;
list.lengthlist.sizeaction.indexuseReducer...stateaction.itemlistReducerstateuseState

Create a free account to access the full topic