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
            Asked
            
        
        
            Active
            
        
            Viewed 65 times
        
    1
            
            
        - 
                    1Pass a function via props from parent to child. – Ori Drori May 22 '20 at 06:19
- 
                    1okay but how to pass data from child to parent – Kritish Bhattarai May 22 '20 at 06:20
- 
                    The same way - a function that sets the state of the parent. – Ori Drori May 22 '20 at 06:22
- 
                    Please check this post: [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs/38397755#38397755) – Shubham Khatri May 22 '20 at 06:23
- 
                    1Please review https://reactjs.org/docs/lifting-state-up.html – Drew Reese May 22 '20 at 06:32
1 Answers
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
