1

Sometimes I meet in code of other people constructions that look like this:

const TextField = () => {
  const renderLabel = () => {..}
  const renderInput = () => {...}
  const renderFooter = () => {...}
  
  return (
    <div>
      {
        renderLabel();
        renderInput();
        renderFooter();
      }
    </div>
  )
}

I understand why they use this way, cause it's can be situation when "return" is too small to split it to separate components and at the same time I want it to look more comfortable to udnerstand.

But only one questions here, why everywhere people use functions for these "renderLabel", "renderInput" and so on?

What cons of the way when I just create them as variables
const renderLabel = <div>...</div>
and then render it?

eugenedrvnk
  • 408
  • 1
  • 5
  • 10
  • 1
    *"But only one questions here, why everywhere people use functions for these "renderLabel", "renderInput" and so on?"* The only advantage that jumps out is that if you have branching logic somewhere, you don't create elements you're not going to use, you just don't call the function. (But really, if it's that complex, those should be components, not functions recreated every time `TextField` is called.) – T.J. Crowder Dec 09 '21 at 18:20
  • Side note: They won't be doing quite what you've shown, since that's a syntax error. But probably `
    {renderLabel()}{renderInput()}{renderFooter()}
    `.
    – T.J. Crowder Dec 09 '21 at 18:21
  • because you can do more in the function with a new lexical environment – MWO Dec 09 '21 at 18:22
  • 2
    Does this answer your question? [React: jsx in a variable vs a function vs a separate component](https://stackoverflow.com/questions/67185279/react-jsx-in-a-variable-vs-a-function-vs-a-separate-component) – Randy Casburn Dec 09 '21 at 18:24

1 Answers1

-1

I don't know about those functions in your example, but I use such functions to generate the component that I need depending on a parameter.

For example, when I build tabs content I may write something like this:

layout:

<button onClick={() => setActiveTab('tab1')}>Tab 1</button>
<button onClick={() => setActiveTab('tab2')}>Tab 2</button>

<div>{generateTabContent(activeTab)}</div>

generate tab content function:

function generateTabContent(activeTab) {
  switch (activeTab) {
    case 'tab1':
      return <Tab1 />
    // etc...
  }
}

This function is pure (it accepts the param, instead of calling the state value), and can be extracted to utils folder if needed.

flppv
  • 4,111
  • 5
  • 35
  • 54