Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to access child components value in parent component in React JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 85
    Answer it

    Currently I am using react create app to build my application in my application had three component those are com1, com2, com3 I want to update userId state value in com1 based on com3 will receive props here com2 is child component of com1.

    Here is the sample code

    import comp2 from './comp2.js';
    class comp1 extends React.Component {
        constructor(props) {
            super(props);
    
              this.state = {
              userId:""
    
             }
            };
    
        click() {
            this.setSate({userId:"123"});
        }
    
        render() {
              <div>Hello Child onClick={this.click}</>
              <comp2 data={this.state.userId}
        }
    }
    
    import comp3 from './comp3.js';
    class comp2 extends React.Component {
        constructor(props) {
            super(props);
            };
    
            componentWillReceiveProps(nextProps) {
            if (nextProps.data !== this.props.data) {
             this.setState({userID:this.state.userId});
           }
     }
    }
    
    
        click() {
             this.setState({userID:"456"})
        }
    
        render() {
              <div>Hello Child onClick={this.click}</>
              <comp3 data={this.state.userId}
        }
    }
    
    class comp3 extends React.Component {
        constructor(props) {
            super(props);
            };
    
        componentWillReceiveProps(nextProps) {
            if (nextProps.data !== this.props.data) {
             this.setState({userID:this.state.userId});
           }
     }
    
        render() {
              <div>Hello Child onClick={this.click}</>
              <comp3 data={this.state.userId}
        }
    }

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: