Jay Hu
Jay Hu

Reputation: 93

How to dynamically change the react element in jsx

I would like to refactor some legacy code. The use case is this. Someone previously had created a new component that basically had all the exact same attributes as the old component. The render method returns either old or new based on a flag, but the attribute values are all the same. This results in many redundant lines that were copy pasted.

  return (
         isSomeBoolTrue ? (<OriginalComponent a={a} b={b} ..... z={z} />):
                          (<NewComponent a={a} b={b} ..... z={z} />)
    );

I'd like some way to remove the duplicate attributes and have it look something like this:

return (isSomeBoolTrue ? (<OriginalComponent):(<NewComponent) a={a} b={b} .... />

Upvotes: 3

Views: 2044

Answers (2)

Adarsh Singh
Adarsh Singh

Reputation: 146

You can also try the following approach.

const SelectedComponent = isSomeBoolTrue ? OriginalComponent : NewComponent;
return <SelectedComponent a={a} b={b} z={z} />

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370659

One option is to put the props into an object, then spread the object into the each component's props while using the conditional operator.

const propsToPassDown = { a, b, z };
return (
  isSomeBoolTrue
    ? <OriginalComponent {...{ propsToPassDown }} />
    : <NewComponent {...{ propsToPassDown }} />
);

Another approach is to use React.createElement instead of JSX, allowing you to use the conditional operator when selecting the component to pass as the first argument.

return React.createElement(
  isSomeBoolTrue ? OriginalComponent : NewComponent,
  { a, b, z },
  null
);

Upvotes: 1

Related Questions