Reputation: 685
I want to pass the Child component state
to parent component state
, I was done once in a class base component but in the functional component, it doesn't work anymore.
Here is my model below:
And that is the components
const Search = () => {
return(
<div>
<h1>Search Anything</h1>
<form>
<InuptForm />
<input type="submit">Search</input>
</form>
</div>
);
}
const InuptForm = () => {
const [search, setSearch] = React.useState('');
const handleChange = (e) => {
setSearch(e.target.value);
}
return(
<div>
<h1>Search Anything</h1>
<form>
<input type="text" name="search" value={search} onChange={handleChange} />
</form>
</div>
);
}
Or is there any chance to use
useReducer
hook to overcome the issue?
I would really appreciate it if anyone can help.
Thanks
Upvotes: 1
Views: 147
Reputation: 961
States cannot be passed to Parent components from child component, instead what you can do is create state in parent component and then pass it as prop to child, so on change function in child will update state in parent component.
const Search = () => {
const [search, setSearch] = React.useState('');
const handleChange = (e) => {
setSearch(e.target.value);
}
return(
<div>
<h1>Search Anything</h1>
<form>
<InuptForm value={search} handler={handleChange} />
<input type="submit">Search</input>
</form>
</div>
);
}
const InuptForm = ({value, handler}) => {
return(
<div>
<h1>Search Anything</h1>
<form>
<input type="text" name="search" value={value} onChange={(e) => handler(e)} />
</form>
</div>
);
}
Upvotes: 0
Reputation: 7642
you cant pass state upwards in React. it is one-directional. if you want the state in the parent you need to "lift the state up". that means place it in the parent component
do something like this:
const Search = ({ handleChange }) => {
return(
<div>
<h1>Search Anything</h1>
<form>
<input type="submit" onChange={handleChange}>Search</input>
</form>
</div>
);
}
const InuptForm = () => {
const [search, setSearch] = React.useState('');
const handleChange = (e) => {
setSearch(e.target.value);
}
return(
<div>
<Search handleChange={handleChange} />
</div>
);
}
I'm rendering <Search />
inside <InputForm />
here and then passing down the handleChange
prop
Upvotes: 3