in my react code when I am trying to run the code it is showing the event is deprecated for the event.preventDefault(). Can anyone tell me what should I do?
import React, { useState } from "react";
function App() {
const [task, setTask] = useState("");
const [todo, setTodo] = useState([]);
function createTodo() {
event.preventDefault();
setTodo((oldTodo) => {
return [...oldTodo, task];
});
}
return (
<div>
<h1>Todo App</h1>
<form onSubmit={createTodo}>
<input
type="text"
value={task}
onChange={(e) => {
setTask(e.target.value);
}}
/>
<button type="submit">Click me</button>
</form>
<ul>
{todo.map((todos) => {
return <li>{todos}</li>;
})}
</ul>
</div>
);
}
export default App;
ERROR in src\App.js Line 8:5: Unexpected use of 'event' no-restricted-globals
CodePudding user response:
You haven't made event an argument to createTodo, so it's being interpreted as a global, hence the warning.
CodePudding user response:
You are using two kinds of events here. The non-deprecated one you used in this bit of code:
onChange={(e) => {
// e is event!
setTask(e.target.value);
}}
To clarify, the code above is really doing this:
onChange={(event) => {
setTask(event.target.value);
}}
But since the event object is passed as argument you can name it anything you like in your function definition:
onChange={(foo) => {
// foo is event!
setTask(foo.target.value);
}}
However, for readability reasons it is best to give the event object an easily recognisable name such as event
or e
.
Now, since you already know how to use the non-deprecated event object all you need to do is do the same thing:
function createTodo(e) {
e.preventDefault();
setTodo((oldTodo) => {
return [...oldTodo, task];
});
}