jesica
jesica

Reputation: 685

How to pass child component state to parent component state in React.js functional components?

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:

enter image description here

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

Answers (2)

Rohit Ambre
Rohit Ambre

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

Red Baron
Red Baron

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

Related Questions