1

I want to invoke the function good without calling it from a event. It should run as soon as page opened just like in the self invoking javascript function. Here is an example

import React from 'react';

class App extends React.Component {

   good(){
      console.log('I was triggered during good')
   }

   render() {
       console.log('I was triggered during render')
       return(
          <div>
             good();  
          </div>
      );
   }
}

export default App;
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142

2 Answers2

5

Few Points:

1. You need to use this keyword to call any function from any other function.

2. To put js code inside JSX, we need to use {}.

Write it like this:

import React from 'react';

class App extends React.Component {

    good(){
        console.log('I was triggered during good')
        return <div> Hello </div>
    }

    render() {
        console.log('I was triggered during render')
        return(
            <div>
                {this.good()}
            </div>
        );
    }
}

Check React DOC: https://facebook.github.io/react/docs/introducing-jsx.html

Check these answers for more details:

How does the "this" keyword work?

What do curly braces mean in JSX (React)?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

You can also use lifecycle methods as componentDidMount(){} or componentWillMount(){}.

componentWillMount will be triggered before mounting of component and componentDidMount() will be triggered after component has been mounted.

Vinay Chaudhary
  • 318
  • 1
  • 6