Building a Simple To-Do List with React

  Building a Simple To-Do List with React


Overview: In this blog post, we'll walk through the process of building a simple to-do list application with React. We'll cover the basics of creating a new React project, defining the components for our application, and implementing the functionality to add and remove items from the list.


Code Snippet:


jsx


import React, { useState } from 'react';


function TodoList() {

  const [items, setItems] = useState([]);

  const [newItem, setNewItem] = useState('');


  const handleAddItem = () => {

    if (newItem.trim() !== '') {

      setItems([...items, newItem]);

      setNewItem('');

    }

  };


  const handleRemoveItem = (index) => {

    const newItems = [...items];

    newItems.splice(index, 1);

    setItems(newItems);

  };


  return (

    <div>

      <h2>To-Do List</h2>

      <ul>

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

          <li key={index}>

            {item}

            <button onClick={() => handleRemoveItem(index)}>Remove</button>

          </li>

        ))}

      </ul>

      <div>

        <input

          type="text"

          value={newItem}

          onChange={(event) => setNewItem(event.target.value)}

        />

        <button onClick={handleAddItem}>Add Item</button>

      </div>

    </div>

  );

}


export default TodoList;

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...