Reputation: 15
I'm only starting to work with React and now trying to create "To Do List", now I need to pass value from input in child functional component to parent functional component, but don't know how to do that.
I need to pass 'value' from 'Form' component to 'App' component to add new value to values array, but components are in different files.
Parent component code:
const App = () => {
const [items, setItems] = React.useState([
'First To Do',
'Second To Do',
'Third To Do',
]);
return (
<div className='app'>
<Form />
<ToDoList items={items} />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Child component code:
const Form = () => {
const [value, setValue] = React.useState('');
function handleValueChange(e) {
setValue(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
console.log(value);
alert('New To Do was added.');
setValue('');
}
return (
<div className={classes.addingForm}>
<form onSubmit={handleSubmit}>
<input className={classes.myInput} type='text' value={value} onChange={handleValueChange}/>
<input className={classes.mySubmit} type='submit' value='Submit' />
</form>
</div>
)
};
export default Form;
Upvotes: 1
Views: 935
Reputation: 46
Define value and setValue in the App component and pass it as props to Form component
// App.js
const App = () => {
const [items, setItems] = React.useState([
"First To Do",
"Second To Do",
"Third To Do",
]);
const [value, setValue] = React.useState("");
useEffect(() => {
// you can log the new value here if the form is submitted
console.log(value);
}, [value]);
return (
<div className="app">
<Form setValue={setValue} />
<ToDoList items={items} />
</div>
);
};
// Child component code:
const Form = ({ setValue }) => {
function handleValueChange(e) {
setValue(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
console.log(value);
alert("New To Do was added.");
setValue("");
}
return (
<div className={classes.addingForm}>
<form onSubmit={handleSubmit}>
<input
className={classes.myInput}
type="text"
value={value}
onChange={handleValueChange}
/>
<input
className={classes.mySubmit}
type="submit"
value="Submit"
/>
</form>
</div>
);
};
export default Form;
Upvotes: 1