DEV Community

loading...

Discussion on: Conditionally render react components in cleaner way

Collapse
lukeshiru profile image
△ LUKE知る

Not necessarily. It can be changed to look something like this:

import { createElement } from "react";

export const RoleSettings = {
  admin: AdminSettings,
  user: UserSettings,
  guest: GuestSettings,
};

export const Settings = ({ userRole, username }) => (
  <div>
    <h1>Settings</h1>
    <p>{createElement(RoleSettings[userRole], { username })}</p>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

or this:

export const roleSettings = {
  admin: AdminSettings,
  user: UserSettings,
  guest: GuestSettings,
};

export const Settings = ({ userRole, username }) => {
  const RoleSettings = roleSettings[userRole];
  return (
    <div>
      <h1>Settings</h1>
      <p>
        <RoleSettings username={username} />
      </p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In both snippets you make use of the "enum solution", and only create the instance of the component you're actually using :D

Collapse
ms_yogii profile image
Yogini Bende Author

Yeah. That's a good way to optimise when you are dealing with large components! We can modify the enum solutions more creatively to achieve both performance as well as simplicity of code.