Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - How do you call a function from inside another function

Suppose I had this layout below:

class Navigation extends React.Component {
 primaryFun() { console.log('funn') }

 secondaryFun() {
  this.primaryFun();
 }
}

I'd of expected this to then call primary but instead I get an undefined, Ok.

So I thought I'd add a constructor to bind the function to this:

constructor(props) {
 super(props)
 this.primaryFun = this.primaryFun.bind(this);
}

but primary fun is still undefined.

In my real project I'm calling these on a mouseOut event.

Feels like the above should work and tbh the documentation for React is all over the shot so couldn't find much here.

like image 688
MaxwellLynn Avatar asked Jul 30 '26 01:07

MaxwellLynn


2 Answers

Are you looking for something like this calling one function inside the other

import React, { Component } from 'react';
import './App.css'

class App extends Component {
  constructor(){
    super()
    this.mouseClick = this.mouseClick.bind(this);
    this.primaryFun = this.primaryFun.bind(this);
    this.secondaryFun = this.secondaryFun.bind(this);
  }

  primaryFun(){
    console.log('primaryFun funn') 
  }

  secondaryFun(){
    console.log('secondaryFun funn') 
    this.primaryFun()
  }

  mouseClick(){
    this.secondaryFun()
  }

  render() {
    return (
      <div onClick={this.mouseClick}>   
      Hello World!
      </div>
    );
  }
}
export default App;

Here when you click on "Hello world" secondaryFun is called and inside secondaryFun , primaryFun is been triggered

like image 173
Harsh Makadia Avatar answered Jul 31 '26 16:07

Harsh Makadia


You also need to bind the secondaryFun function to use this inside that. Without that, the this inside the function secondaryFun will refers to the function scope which is secondaryFun

like image 26
Sagar Jajoriya Avatar answered Jul 31 '26 15:07

Sagar Jajoriya