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;
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;
Share
Improve this question
edited Jun 5, 2017 at 16:56
Mayank Shukla
105k19 gold badges162 silver badges145 bronze badges
asked Jun 5, 2017 at 16:49
Sambit Kumar SahuSambit Kumar Sahu
111 gold badge1 silver badge3 bronze badges
2 Answers
Reset to default 5Few 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)?
You can also use lifecycle methods as ponentDidMount(){} or ponentWillMount(){}.
ponentWillMount will be triggered before mounting of ponent and ponentDidMount() will be triggered after ponent has been mounted.