How do I call a method from another class component in React.js

74,684

Solution 1

Here you go

Class1.js

       export class Class1 extends Component {
             render() {
                return (
                    <div onClick={this.props.callApi}></div>
                )
            }
       }

Class2.js

  1. Either bind callApi function in constructor or change it to arrow function.
  2. Passdown callApi method to class1 component as a prop and access it in the above component as this.props.callApi and pass it to onClick of div.

     export class Class2 extends Component {
           callApi = () => {
               Here I call my API, I set & call states, ...
            }
           render {
               return (
                  <Class1 callApi={this.callApi} />
                       Here I return my API content
                )    
           }   
       }
    

Solution 2

How do i call a method from another class component in react.js

Using Props

"render prop" refers to a technique for sharing code between React components uising a prop whose value is a function" - reactjs.org

Example

app.js

import Button from '../../pathtoButton';
export class App extents Component {
    constructor(props){
        super(props)
        this.state = {
             name:'John'
        }
    }
    sayHello(){
        const { name } = this.message;
        alert(`Hello ${name}`}
    }
    render(){
        return (
             <div>
                 <Button
                     value="click me"
                     whenClicked={this.sayHello}
             </div>
        );
    }
}

button.js

export class Button extents Component {
    constructor(props){
        super(props)
        this.state = {
             style:{background:'red', color:'white'},
        }
    }
    render(){
        const { style } = this.state;
        const { whenClicked, value} = this.props;
        return (
             <div>
                 <button style={style} onClick={whenClicked}>{value}</button>
             </div>
        );
    }
}

Explanation

In app.js we imported the component <Button/> and using props we passed a method from app.js "sayHello" to a prop we created called whenClicked. In button.js we referenced this.props.whenClicked and passed it to the onClick property.

sayHello is now being shared between the two components because we passed the method as a prop to the <Button/> component.

Share:
74,684
Cédric Bloem
Author by

Cédric Bloem

Just a graphic designer and frontend developer who likes to explore multiple code languages depending on what I want to achieve.

Updated on July 09, 2022

Comments

  • Cédric Bloem
    Cédric Bloem almost 2 years

    So I have to class components:
    Class1: has a clickbutton
    Class2: has a method calling my api

    Basically, what I want is to call a method that sets and edits states inside one class from another class. But I keep failing.

    Example:

    Class1.js
    export class Class1 extends Component {
       render() {
          return (
             <div onClick={must call Class2Method}></div>
          )
       }
    }
    
    Class2.js
    export class Class2 extends Component {
       Class2Method(){
          Here I call my API, I set & call states, ...
       }
       render {
          return (
             <Class1 />
             Here I return my API content
          )    
       }   
    }
    

    What I tried:

    1. I have tried to use my method and call and set my states in my App.js (parent of both class2 and class1); but then my Class2.js console says it can't find my states.
    2. I also tried: < Class1 method={this.Class2Method} /> in my Class 2 and < div onClick={this.props.method} > in Class1.
  • djamaile
    djamaile over 5 years
    <Class1 callApi={() => this.callApi()}/>
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    Peter it’s not mandatory but it’s good to have that when we want to prevent the event handler function gets called on every render and also when we want to pass parameters to the function. Correct me if I am wrong
  • djamaile
    djamaile over 5 years
    No, your understanding it right! But i thought it would be helpful.
  • Cédric Bloem
    Cédric Bloem over 5 years
    Oh my god this worked; thanks so much! Can someone explain me why it works with an arrow function but not with a basic method?
  • Cédric Bloem
    Cédric Bloem over 5 years
    The solution of Hemadri Dasari did the trick; but your comment about 'Consider to use Stateless Functional Components instead of...' has caught my attention. I'm gonna take a look at that article and try to understand how this could help me to avoid future problems
  • Hemadri Dasari
    Hemadri Dasari over 5 years
    All event handler functions in component needs manual binding or Make them as arrow functions. Because binding is needed to access this context inside the function or arrow function has this context available