Akshata
Akshata

Reputation: 15

How to call the parent Method in child class component in react

    //child component
    import React, { Component } from 'react'
    const NavButton = ({ active, title, href, onSetActive }) => {
        return (
            <button
                className={active ? "btn btn-light regular-btn active" : "btn btn-light regular-btn"}
                href={href}
                onClick={onSetActive} >
                {title}
            </button>
        )
    }
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {
                activeIndex: 1,
                buttons: [
                    {
                        title: "1",
                        key: 0,
                        value: 1
                    },
                    {
                        title: "3",
                        key: 1,
                        value: 3
                    }
                ]
            }
        }
       //It was changing active index
        handleChangeActive(newActiveIndex) {
            // console.log("Working");
            this.setState({ activeIndex: newActiveIndex });
        }
    
        render() {
            const { activeIndex } = this.state;
            return (
                <div>
                    <nav id="navbarMain">
                        <div className="navbar-nav flex-row">
                            {this.state.buttons.map((button, buttonIndex) =>
                                /* determine which nav button is active depending on the activeIndex state */
                                <NavButton onClick={() => this.investmentHandler.bind(this)} value={button.value} onSetActive={() => this.handleChangeActive(buttonIndex)} active={buttonIndex === activeIndex} title={button.title} key={button.key} />)}
    
                        </div>
                    </nav>
                </div>
            )
        }
    }
    
    export default Child
    
    
    // parent component
    import React, { Component } from 'react'
    import Child from './Child';
    class Parent extends Component {
        constructor(props) {
            super(props)
    
       

 this.state = {
            firstValue: 1,
            secondValue: 3,
            result: ''
        }
        
        // this.add = this.add.bind(this);
    }
//calculating the input values
    Add = () => {
        var { firstValue, secondValue, result } = this.state;

        result = firstValue + secondValue;
        console.log(result);
        document.getElementById("result").innerHTML = result;
    }
    render() {
        return (
            <>
//Child component is used inside the parent component using props

                <Child investmentHandler={this.add} />
                <p id="result">Result</p>
            </>
    
            )
        }
    }
    export default Parent

I need the event handler(Add) has to work inside the child component. How to use event handler using props in class components. How to call the parent Method in child class component in react. I was tried using props but it was not working. Based on the child component input button it has to get the result.

Upvotes: 1

Views: 849

Answers (2)

Danilson Reis
Danilson Reis

Reputation: 121

On Child class your component NavButton has an onClick attribute that calls onSetActive, so you can call investmentHandler on the onSetActive function:

//child component
import React, { Component } from "react";
const NavButton = ({ active, title, href, onSetActive }) => {
  return (
    <button
      className={
        active
          ? "btn btn-light regular-btn active"
          : "btn btn-light regular-btn"
      }
      href={href}
      onClick={onSetActive}
    >
      {title}
    </button>
  );
};
class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeIndex: 1,
      buttons: [
        {
          title: "1",
          key: 0,
          value: 1,
        },
        {
          title: "3",
          key: 1,
          value: 3,
        },
      ],
    };
  }
  //It was changing active index
  handleChangeActive(newActiveIndex) {
    // console.log("Working");
    this.setState({ activeIndex: newActiveIndex });
    this.props.investmentHandler();
  }

  render() {
    const { activeIndex } = this.state;
    return (
      <div>
        <nav id="navbarMain">
          <div className="navbar-nav flex-row">
            {this.state.buttons.map((button, buttonIndex) => (
              /* determine which nav button is active depending on the activeIndex state */
              <NavButton
                value={button.value}
                onSetActive={() => this.handleChangeActive(buttonIndex)}
                active={buttonIndex === activeIndex}
                title={button.title}
                key={button.key}
              />
            ))}
          </div>
        </nav>
      </div>
    );
  }
}

export default Child;

On the Parent class when getting the props from the Child class you was calling "this.add" when you should be calling "this.Add":

// parent component
import React, { Component } from 'react'
import Child from './Child';
class Parent extends Component {
    constructor(props) {
        super(props)

this.state = {
        firstValue: 1,
        secondValue: 3,
        result: ''
    }
    
    // this.add = this.add.bind(this);
}
//calculating the input values
Add = () => {
    console.log('Im here')
    var { firstValue, secondValue, result } = this.state;

    result = firstValue + secondValue;
    console.log(result);
    document.getElementById("result").innerHTML = result;
}
render() {
    return (
        <>
            <Child investmentHandler={this.Add} />
            <p id="result">Result</p>
        </>

        )
    }
}
export default Parent

I made this few changes and the code worked for me.

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Check this might help

 //child component
    import React, { Component } from 'react'
    const NavButton = ({ active, title, href, onSetActive }) => {
        return (
            <button
                className={active ? "btn btn-light regular-btn active" : "btn btn-light regular-btn"}
                href={href}
                onClick={onSetActive} >
                {title}
            </button>
        )
    }
    class Child extends Component {
        constructor(props) {
            super(props);
            this.state = {
                activeIndex: 1,
                buttons: [
                    {
                        title: "1",
                        key: 0,
                        value: 1
                    },
                    {
                        title: "3",
                        key: 1,
                        value: 3
                    }
                ]
            }
        }
       //It was changing active index
        handleChangeActive(newActiveIndex) {
            // console.log("Working");
            this.setState({ activeIndex: newActiveIndex });
        }
    
        render() {
            const { activeIndex } = this.state;
            return (
                <div>
                    <nav id="navbarMain">
                        <div className="navbar-nav flex-row">
                            {this.state.buttons.map((button, buttonIndex) =>
                                /* determine which nav button is active depending on the activeIndex state */
                                <NavButton onClick={() => this.props.investmentHandler()} value={button.value} onSetActive={() => this.handleChangeActive(buttonIndex)} active={buttonIndex === activeIndex} title={button.title} key={button.key} />)}
    
                        </div>
                    </nav>
                </div>
            )
        }
    }
    
    export default Child
    
    
    // parent component
    import React, { Component } from 'react'
    import Child from './Child';
    class Parent extends Component {
        constructor(props) {
            super(props)
    
       

 this.state = {
            firstValue: 1,
            secondValue: 3,
            result: ''
        }
        
        // this.add = this.add.bind(this);
    }
//calculating the input values
    Add = () => {
        var { firstValue, secondValue, result } = this.state;

        result = firstValue + secondValue;
        console.log(result);
        document.getElementById("result").innerHTML = result;
    }
    render() {
        return (
            <>
//Child component is used inside the parent component using props

                <Child investmentHandler={this.Add} />
                <p id="result">Result</p>
            </>
    
            )
        }
    }
    export default Parent

Upvotes: 0

Related Questions