Here is an example of what the todos.js file might look like:
import React, { useState } from 'react'
export default function Todos() {
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState('')
function handleSubmit(e) {
e.preventDefault()
setTodos([...todos, newTodo])
setNewTodo('')
}
function handleDelete(index) {
setTodos(todos.filter((_, i) => i !== index))
}
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={newTodo}
onChange={e => setNewTodo(e.target.value)}
placeholder="Add a new todo"
/>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleDelete(index)}>Delete</button>
</li>
))}
</ul>
</div>
)
}
This code uses the useState hook to initialize a state variable for the todo list and a state variable for the new todo being added. The handleSubmit function pushes the new todo to the state array and the handleDelete function filters the todo out of the state array, which will update the list of todos being displayed.
The form uses the onSubmit event, the input uses onChange event to update the state of newTodo and the delete button uses onClick event to delete the respective todo.
This is a very basic example, and you may want to add additional functionality such as editing todos or marking them as complete.
No comments:
Post a Comment