import React from "react";
export default function Form ({handleSubmit, handleChange, value}) {
return (
<form onSubmit = {handleSubmit}>
<label>
<input type="text" name="name" onChange = {handleChange}/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
I'm trying to create a basic ToDoList App. I'm getting stuck on the part in which you render the users input into my ToDoList Component. When I alert the value of e.target.value I get undefined. What is the problem? EDIT: Added my form component.
import "./styles.css";
import Header from "./Header.js";
import Form from "./Form.js";
import {useState} from "react";
import ToDoList from "./ToDoList.js"
export default function App() {
const[items, setItems] = useState([]);
let value = "";
function handleChange(e) {
value = e.target.value;
}
function handleSubmit(e) {
setItems([...items,
e.target.value
]);
alert('A name was submitted: ' e.target.value);
e.preventDefault();
}
return (
<div className="App">
<div>
<Header/>
</div>
<div>
<Form handleChange = {handleChange} handleSubmit = {handleSubmit} value = {value}/>
</div>
<div>
<ToDoList items = {items}/>
</div>
</div>
);
}
CodePudding user response:
Because you pass whole form as event to handleSubmit
and items
. If you want to keep this style of code, you must use input value changes. Also you must define e.preventDefault()
before doing everything. So:
import "./styles.css";
import Header from "./Header.js";
import Form from "./Form.js";
import {useState} from "react";
import ToDoList from "./ToDoList.js"
export default function App() {
const[inputValue, setInputValue] = useState();
const[items, setItems] = useState([]);
let value = "";
function handleChange(e) {
setInputValue(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
setItems([...items,
inputValue
]);
setInputValue("");
alert('A name was submitted: ' e.target.value);
}
return (
<div className="App">
<div>
<Header/>
</div>
<div>
<Form handleChange={handleChange} handleSubmit={handleSubmit} value = {value}/>
</div>
<div>
<ToDoList items = {items}/>
</div>
</div>
);
}