Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a component in JSX vs via function

When using React, what is the difference (and when should each method be applied) when rendering a component?

Does this impact the component lifecycle in any way? Or impact how hooks are run in the component?

Method 1:

class App extends React.Component {
  ...
  function getComponent() {
    return <Component />
  }
  render() {
   return this.getComponent()
  }
}

Method 2:

class App extends React.Component {
  ...
  render() {
   return <Component />
  }
}
like image 688
Charklewis Avatar asked Dec 14 '22 09:12

Charklewis


1 Answers

(Note: The OP has now changed the question, it used to have return {this.getComponent()} in Method 1.)

render in Method 1 is incorrect (well, it was before the edit), it should be:

render() {
  return this.getComponent() // No {} wrapper
}

You need the {} within a JSX context, but you're not in a JSX context there. For instance, if you wanted to wrap what this.getComponent returned in a div, you'd use the JSX expression to define the div's children within the JSX defining the div:

render() {
  return <div>{this.getComponent()}</div>
}

With the {} sorted out, whether you use Method 1 or Method 2 is up to you. If you have substantial parts of the render that you want to move into their own functions, that's fine. For instance:

render() {
    return (
        <div>
            {this.getHeader()}
            {this.getBody()}
            {this.getFooter()}
        </div>
    );
}

...although I think I'd probably argue at that point that without a good counter-argument, the header, body, and footer should probably be components (perhaps function components). But the occasional helper function call like that is fine.

Does this impact the component lifecycle in anyway?

No. It's just a function call within render.

like image 169
T.J. Crowder Avatar answered Dec 25 '22 17:12

T.J. Crowder