1

How to change parent component's state from child component?, Also I need to pass some data from child component. Any help is greatly appreciated, thank you

Kritish Bhattarai
  • 1,501
  • 15
  • 20

1 Answers1

1

Try to understand from this example

const Parent = ()=>{
    const [name,setName]=useState("");
    const handleName = (name)=>setName(name);
    const inputProps= {
        handleName:handleName
    }
    return (
        <>
            <div>My name is :{name}
            <Child props={inputProps} />
        </>
    )
}

const Child =(props)=>{
    const[name,setName]=useState("");
    useEffect(()=>
       props.handleName(name);  
    },[name])
    return(
        <input type="text" placeholder="Enter your name" 
        value={name} onChnage={(e)=>setName(e.target.value)} 
        />
    )
}

In this example the Parent Component Changes its state based on the changes in the Child Component. Child Component is just a input tag, on change of which triggers the effect hook which passes the value to the parent handler passed as a props. and displays the changed state.

I hope this helps!!

Kartikeya Sharma
  • 553
  • 1
  • 5
  • 22