Search code examples
javascriptreactjsreact-propsreact-component

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.


Solution

  • 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}/>;
    }