1

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.

2
  • how do you decide proplist value ? is already handled or you need to handle based on isPresent ? Commented Sep 15, 2019 at 16:21
  • The props values have nothing to do with isPresent. Commented Sep 15, 2019 at 16:22

2 Answers 2

3

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}/>;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - that did it.
2

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

1 Comment

Thanks - much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.