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.
useReducer
Dynamic list
Report a typo
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;Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.