Home > database >  Calling a Component via const or JSX
Calling a Component via const or JSX

Time:08-12

Is there a preferred way to call a component in React? eg. setting it as a constant vs calling it in jsx?

  function getAnimalGalleryPicture() {
    ... return <LionPicture/>
    ... return <FishPicture/>
    ... return <DogPicture/>

  }

  const animalGalleryPicture = getAnimalGalleryPicture();
  return <>{animalGalleryPicture}</>;

vs:

  return <>{getAnimalGalleryPicture()}</>;

CodePudding user response:

An option that's better than both would be to make the function that returns a component into a component itself.

function AnimalGalleryPicture() {
    if (condition) return <LionPicture/>;
    if (condition2) return <FishPicture/>;
    return <DogPicture/>;
}

and then you just do

<AnimalGalleryPicture />

calling it as a component, instead of like any old function.

CodePudding user response:

JSX can be assigned to variables and passed like variables.

const things = (<>
    <LionPicture/>
    <FishPicture/>
    <DogPicture/>
</>)

// ...

return <>{things}</>

However, with something so simple, youd usually inline it. You only need to split things out like that if you need to call into it in multiple places, or with different parameters. In this case, youd also usually declare a new component with that stuff in, rather than a method that returns it.

A function which returns JSX is pretty much in an of itself a component -- you just need to name it as such and hoist that function out of your render to make it top level. So instead of getAnimalGalleryPicture, do:

const AnimalGalleryPicture = () => <>
    <LionPicture/>
    <FishPicture/>
    <DogPicture/>
</>

Then use that component where you need.

<AnimalGalleryPicture />

Doing this is preferable -- components defined at the top level are more performant than functions nested inside of components and then called.

  • Related