Reputation: 43
I am building a simple to do list in react where I want to store element on submit.I know something is wrong with the handleSubmit() but unable to solve it.
import React, { useState } from "react";
function List() {
const [items, setItems] = useState([]);
const [item, setItem] = useState("");
function handleSubmit() {
setItems([ ...items, item ]);
console.log(items);
}
return (
<div>
<h3>To Do List</h3>
<form onSubmit={handleSubmit()}>
<input
value={item}
onChange={(event) => {
setItem(event.target.value);
}}
/>
<ul>
<li></li>
</ul>
<button type="submit">Add</button>
</form>
</div>
);
}
export default List;
Upvotes: 0
Views: 137
Reputation: 161
You are calling handleSubmit
function directly instead of passing its reference.
just change <form onSubmit={handleSubmit()}>
to <form onSubmit={handleSubmit}>
Also you need to preventDefault form submit action. You can add the preventDefault line in your handleSubmit function
function handleSubmit(event) {
event.preventDefault();
setItems([ ...items, item ]);
console.log(items);
}
Upvotes: 0
Reputation: 136
<form onSubmit={handleSubmit()}>
should be <form onSubmit={handleSubmit}>
.
By adding ()
you are calling handleSubmit
Upvotes: 1