简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM