I’m new to React and js in general and I’m following a crash course on React on got stuck on this error at some point in the course, and I’m getting this error for the preventDefault method that I have used to prevent the page from refreshing.
here is the 2 file concern
import { useState } from "react"
export function NewTodoForm({onSubmit}){
const [newItem, setNewItem] = useState("")
function handleSubmit(e) {
e.preventDefualt()
if (newItem === "") return
onSubmit(newItem)
setNewItem("")
}
return (
<form className="new-item-form" onSubmit={handleSubmit}>
<div className="form-row">
<label htmlFor="item"> New Item</label>
<input value={newItem} onChange={e => setNewItem(e.target.value)} type="text" id="item"></input>
</div>
<button className="btn" >
Add
</button>
</form>
)
}
import "./styles.css"
import { useState } from "react"
import { NewTodoForm } from "./NewTodoForm"
function App() {
const [todos, setTodos] = useState([])
function addTodo(title) {
setTodos(currentTodos => {
return [
...currentTodos,
{ id: crypto.randomUUID(), title, completed: false },
]
})
}
console.log(todos)
return (
<>
<NewTodoForm onSubmit={addTodo}/>
<h1 className="header">
Todo List
</h1>
<ul className="list">
{todos.map(todo => {
// eslint-disable-next-line react/jsx-key
return (
<>
<li key={todo.id}>
<label>
<input type="checkbox" checked={todo.completed}/>
{todo.title}
</label>
<button className="btn btn-danger">
delete
</button>
</li>
</>
)
})}
</ul>
</>
)
}
export default App
I tried to use other methods rather than preventDefualt, but none of them works, from preventing from refreshing the page.
2
Answers
You have a typo, your code is
It should be
The issue is in handleSubmit function where e.preventDefault() has been misspelled. Also don’t forget to make "default" export of your function.