React Dynamic List with Example

In React, dynamic lists are essential for displaying and managing data that can change over time. We achieve dynamic list functionality using React’s useState hook, which allows us to manage state within functional components.

In this guide, we’ll explore how to create and delete items in a dynamic list using React and the useState hook.

React Dynamic List with Example

Understanding useState Hook

import { useState } from “react”;

const [data, setData] = useState([“sarwar”, “zaky”, “ahmad”]);

const [inputValue, setInputValue] = useState(“”);

In the above code, we import the useState hook from the React library. We use useState to declare two state variables: data, which holds the list items, and inputValue, which captures user input for adding new items to the list.

Creating a Dynamic List

{data.map((item, index) => (

 <p key={index}>{item}</p>

))}

Here, we use the map method to iterate over the data array and render each item as a paragraph (<p>) element. The key attribute is necessary to uniquely identify each item in the list and optimize React’s rendering performance.

Adding Items to the List

const addItem = () => {

 setData([...data, inputValue]);

 setInputValue("");

};

In the addItem function, we update the data state by appending the inputValue to the existing list using the spread operator (…). We then reset the inputValue state to an empty string, clearing the input field.

Deleting Items from the List

const deleteItem = () => {

 setData(data.filter(item => item !== inputValue));

 setInputValue("");

};

To delete an item from the list, we use the filter method to create a new array excluding the item to be deleted based on its value. We update the data state with the filtered array and reset the inputValue state.

Taking input from the user:

 <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={() => addItem()}> Add </button>

      <button onClick={() => deleteItem()}> Delete </button>

This code snippet provides a text input field (<input>), two buttons (“Add” and “Delete”), and associated event handlers.

  • The text input field captures user input (inputValue) and updates it via the onChange event handler.
  • The “Add” button triggers the addItem function, which adds the current inputValue to the list (data) and clears the input field.
  • The “Delete” button triggers the deleteItem function, which removes an item from the list based on the inputValue.

Overall, this setup allows users to add new items to the list and delete existing items.

Complete code

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [data, setData] = useState(["sarwar", "zaky", "ahmad"]);
  const [inputValue, setInputValue] = useState("");

  const addItem = () => {
    setData([...data, inputValue]);
    setInputValue("");
  };

  const deleteItem = () => {
    data.map((item, index) => {
      if (item === inputValue) {
        data.splice(index, 1);
        setData([...data]);
        setInputValue("");
      }
    });
  };
  return (
    <div className="App">
      <h1> React Dynamic List</h1>
      {data.map((item, index) => (
        <p key={index}>{item}</p>
      ))}

      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={() => addItem()}> Add </button>

      <button onClick={() => deleteItem()}> Delete </button>
    </div>
  );
}

Conclusion

In this guide, we’ve explored how to implement dynamic lists in React using the useState hook. By understanding the useState hook and its capabilities, you can create interactive and responsive lists that adapt to user input and data changes.

Dynamic lists are foundational for building dynamic user interfaces in React, empowering you to create engaging web applications.

Leave a Comment