0

I have a parent component

class ParentComponent extends React.PureComponent {       
       render(){
        return(   
        //IN HERE I'm calling child parent    
          <ChildComponent/>
        )
        }        
        }

class ChildComponent extends React.PureComponent {  
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };  
    }

how can I get the sample state to the parent component?

Prash
  • 27
  • 4

3 Answers3

2
  1. So at the Parent Component make a method which receives value in return.

    StateValue = (value) =>{
     console.log(value);
    } 
    
  2. Pass this method as props to the child component.

    <ChildComponent method={this.StateValue}/>
    
  3. At the child component Pass the state value to the method props received in step 2.

    constructor(props) {
     super(props);
     this.state = {
       sample: 'hi',        
     };  
     }
    
     render(){
       this.props.method(this.state.sample)
    
       return(
         <></>
       )
    

You will get your state value in StateValue Method from the props in your parent component.

Fahad Shinwari
  • 968
  • 7
  • 7
0

Try this:

class ParentComponent extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };  
    }

      render(){
        return(   
          <ChildComponent sample={this.state.sample} setState={(sample) => this.setState({ sample })} />
          )
         }        
        }

class ChildComponent extends React.PureComponent {    
// you can now call this.props.setState(value); to set parent component state.
// and access the sample state: this.props.sample;
    }
Emilio
  • 389
  • 1
  • 8
0

One option is to specify a callback as a prop. Like this:

class ParentComponent extends React.PureComponent {
      onSample = (sample) => {
          // handle sample
       }

       render(){
        return(   
        //IN HERE I'm calling child parent    
          <ChildComponent
            callback={this.onSample}
          />
        )
        }        
      }

class ChildComponent extends React.PureComponent {  
    constructor(props) {
        super(props);
        this.state = {
          sample: '',        
        };
        this.onSample = props.callback
        // call later on via this.onSample(<sample>);
    }
dwosk
  • 1,202
  • 8
  • 11