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;

2 Answers 2

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)?

Sign up to request clarification or add additional context in comments.

2 Comments

Nicely explained... :)
That really helped
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.

1 Comment

Thanks. I will be trying those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.