buydadip
buydadip

Reputation: 9447

child-parent components react (sharing)

I have a link in a particular component...

class Bottom extends React.Component {

    constructor(){
        super();
        this.state = {link:"Don't have an account?"}    
    }

    render(){

        return (
        <div>
            <div className="sub-login">
                <p>{this.state.link}<a onClick={this.props.onClick.bind(null, this)}> Register here</a></p>
            </div>

        </div>

        );
    }
}

export default Bottom;

I added an onClick event handler on the link above. Now, I want the parent component that uses the component above, Bottom, to catch the onClick event.

So in the following component, I want the following...

import Bottom from './register-link.js';

class Index extends React.Component {
    constructor() {
        super();
        this.state = {header:"Welcome to TutorHub"}
    }

    IF CLICKED: console.log("link was clicked");

    render(){   
        return (
        <div>

                <Inputs />   
                <Bottom />    

            </div>


        </div>

        );
    }
}

export default Index;

How can I achieve this?

Upvotes: 0

Views: 279

Answers (1)

Rafi Ud Daula Refat
Rafi Ud Daula Refat

Reputation: 2257

According to the official documentation of react js you can pass functions and values as props from parent to children component. Just pass a function as props named onClick to the Bottom component from the Index component. It will be

<Bottom onClick={this.handleClick.bind(this)}/> 

instead of

<Bottom />

The Full code is given bellow:

class Bottom extends React.Component {

    constructor(){
        super();

        this.state = {link:"Don't have an account?"}    
    }

    render(){

        return (
        <div>
            <div className="sub-login">
                <p>{this.state.link}<a onClick={this.props.onClick.bind(this)}> Register here</a></p>
            </div>

        </div>

        );
    }
}

export default Bottom;


import Bottom from './register-link.js';

class Index extends React.Component {
    constructor() {
        super();
        this.state = {header:"Welcome to TutorHub"}
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick()
    {
      console.log("link was clicked");
    }


    render(){   
        return (
        <div>

                <Inputs />   
                <Bottom onClick={this.handleClick.bind(this)}/>    

            </div>


        </div>

        );
    }
}

export default Index;

Upvotes: 1

Related Questions