Use the onClick event of the button to call a function that pushes the new todo to the state array.
Here's an example of how you might use the onClick event of a button to call a function that pushes the new todo to the state array in the todos.js file:
import React, { useState } from 'react'
export default function Todos() {
const [todos, setTodos] = useState([])
const [newTodo, setNewTodo] = useState('')
function addTodo() {
setTodos([...todos, newTodo])
setNewTodo('')
}
return (
<div>
<form>
<input
type="text"
value={newTodo}
onChange={e => setNewTodo(e.target.value)}
placeholder="Add a new todo"
/>
<button onClick={addTodo}>Add</button>
</form>
</div>
)
}
In this example, we've added a button with the onClick event handler that calls the addTodo function. The addTodo function pushes the new todo to the state array and clears the newTodo variable so that the input field is empty again for the next todo.
This way, we don't need to use the onSubmit event of the form, the user can add a new todo by just click the button, after fill the input field.
It's important to note that since we're using onClick instead of onSubmit, the page will not refresh after the button is clicked, so the new todo will be added to the state array and displayed on the page without refreshing the entire page.
No comments:
Post a Comment