Reputation: 1652
#1 - when to add code on the class?
class WrappedHorizontalLoginForm extends React.Component {
#2 - when to add code on the class?
handleFormSubmit = (event) => {
event.preventDefault();
const user = event.target.elements.user.value;
console.log(user)
};
render() {
# 3 - when to add code in the render?
return (<div>
<Form onSubmit={this.handleFormSubmit}>
</Form.Group>
</div>
Can someone kindly point out cases on when to add a function in the class vs when to add code within the render method vs when to add it outside the class?
Are their generic guidelines to follow in terms of functionality or specific code?
handleFormSubmit
in the code above can be used as an example to explain.
Upvotes: 0
Views: 368
Reputation: 2200
There is no need to put code just before the render method execution - you probably want to use the component life-cycle methods instead.
if you wants to keep working with Classes so you can use the componentWillMount that will execute just before the component is mounted into the dom.
if you want to work with Functional Components so as part of React 16.8 there is a new feature that called React Hooks.
You can read more about it here: https://reactjs.org/docs/hooks-intro.html
Upvotes: 1
Reputation: 3654
Any code in the render method will run when the component rerenders due to a change in state or props etc. So say you have a component which shows a table of data from a database and it has some state of which cells are selected etc. You would not want to run the database get query when you select a cell as it is not changing. So for that you would have the database request in something like componentWillMount
rather than in the render method.
Generally code in the render method is for things such as defining temporary variables or if and else clauses. You want to write most code in the designated react class methods.
Also writing thread blocking code in the render method will reduce the speed of your site.
Upvotes: 2