Moshe
Moshe

Reputation: 6991

Conditional Rendering of Components with Same Props in ReactJS

I have a simple conditional test that I am running to see which component to render. If the condition is true, I render one component, false the other component. Right now this is how my code looks something like this:

    {isPresent && (
        <FirstComponent
          propOne="value one"
          propTwo="value two"
          {...props}
        />
    )}
    {!isPresent && (
        <SecondComponent
          propOne="value one"
          propTwo="value two"
          {...props}
        />
    )}

What I want to know is whether or not I can make this code a bit DRYer. Something like this:

{isPresent && (
    <FirstComponent
        {propList}
    />
)}
{!isPresent && (
    <SecondComponent
        {propList}
    />
)}

Where propList represents all of the props that I want to include in each of these components.

Is this possible? If so, how?

Thanks.

Upvotes: 1

Views: 2460

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use a variable in render to define which component you want to render

 let Comp = isPresent ? FirstComponent : SecondComponent
 let propList = {
    propOne :"value one",
    propTwo : "value two",
    ...props
 }

Then in your return you can use

 <Comp
   { propList }
 />

Note:- Always name the variable with first letter capital if you're assigning it a component, because In JSX, lower-case tag names are considered to be HTML tags

Upvotes: 2

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

If both elements have the same properties, then you can store these properties into a constant and pass it to the target Component

function YourComponent(props) {
  const commonProps = {
      propOne: "value one",
      propTwo: "value two",
      ...props
   };

   const Component = isPresent ? FirstComponent : SecondComponent;
   return <Component {...commonProps}/>;
}

Upvotes: 3

Related Questions