DEV Community

Cover image for Stop rendering conditions like this
abdelrahman seada
abdelrahman seada

Posted on • Updated on

Stop rendering conditions like this

we use conditions everywhere on our applications whether for state check or rendering some data into the view depending on some parameters. in this post will show some of how to render conditions in different way than using regular if(...) else {} blocks or even using ternary condition

for example (1)

type UserType = "admin" | "editor" | "user";

type User = { name: string; type: UserType };

const users: User[] = [
  { name: "john", type: "admin" },
  { name: "mike", type: "editor" },
  { name: "abdelrahman", type: "user" },
];

export default function Test() {
  const actions = ["create", "read", "update", "delete"];

  return (
    <div>
      {users.map((user) => (
        <div key={user.name}>
          {/* we need to render actions depending on user type */}
          <p>{user.name}</p>
          <div className="flex items-center">
            user actions:
            {user.type === "admin" && actions.map((a) => <Action a={a} key={a} />)}
            {user.type === "editor" && actions.filter((a) => a !== "create").map((a) => <Action a={a} key={a} />)}
            {user.type === "user" && actions.filter((a) => a === "read").map((a) => <Action a={a} key={a} />)}
          </div>
        </div>
      ))}
    </div>
  );
}

function Action(props: { a: string }) {
  const { a } = props;
  return <p className="px-2 py-1 border-[1px] mx-2 rounded-md">{a}</p>;
}


Enter fullscreen mode Exit fullscreen mode

output for example (1)

rendering using regular method

in this example we had to make a check condition for each user type to render his actions, as you can see this consumes a lot of code , harder to debug , harder to add more in future lastly looks ugly but this is a better way to do so

example (2)

type UserType = "admin" | "editor" | "user";

type User = { name: string; type: UserType };

const users: User[] = [
  { name: "john", type: "admin" },
  { name: "mike", type: "editor" },
  { name: "abdelrahman", type: "user" },
];

const userActionsStates: Record<UserType, string[]> = {
  admin: ["create", "read", "update", "delete"],
  editor: ["create", "read", "update"],
  user: ["read", "update"],
};

export default function Test() {
  return (
    <div>
      {users.map((user) => (
        <div key={user.name}>
          {/* we need to render actions depending on user type */}
          <p>{user.name}</p>
          <div className="flex items-center">
            user actions:
            {userActionsStates[user.type].map((a) => (
              <Action key={a} a={a} />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function Action(props: { a: string }) {
  const { a } = props;
  return <p className="px-2 py-1 border-[1px] mx-2 rounded-md">{a}</p>;
}


Enter fullscreen mode Exit fullscreen mode

output for example (2)

  • output is the same as example (1)

key changes

grouping each user type in object key and value should be what ever you want to render
in this case we pass each user type actions like the following

grouping in objects

and here instead of rendering each condition like example (1) or making a ternary condition we get user actions from grouped object userActionsStates and just render whatever in the key's value and VoilΓ  it's only one line of code

conditions using object

what about else ? what if we pass a user type that does not exists in the object ?

in this case we can add a default key in the object , this key will be used in false or undefined cases
like the following :


const userActionsStates : Record<UserType , string[] > = {
    admin: ["create", "read", "update", "delete"],
    editor: ["create", "read", "update"],
    user: ["read", "update"],
    default : ["read"]
}


Enter fullscreen mode Exit fullscreen mode

if we updated users with new user that it's type is not defined like the last user object

updated users with new undefined user type

then we will make a small change to the render method

<div className="flex items-center">
  user actions:
  {(userActionsStates[user.type] ?? userActionsStates["default"]).map((a) => (
    <Action key={a} a={a} />
  ))}
</div>

Enter fullscreen mode Exit fullscreen mode

using null coalescing ?? we ensure that it will render as expected on
all conditions. :)

updated users output

please note

using this method you can render anything in the key's value string , number , array , Component , ...etc.

summary

  • easy to read , debug and update πŸ§‘β€πŸ’»
  • looks cool 😌
  • less code

it's up to your creativity and imaginations πŸ’‘πŸ”₯

Top comments (43)

Collapse
 
shricodev profile image
Shrijal Acharya • Edited

Just one simple piece of advice: Instead of using 4 spaces for indentation in code snippets for blogs, I think it's better to use 2 spaces as it reduces the need for horizontal scrolling.

Great read. πŸ‘Œ

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks for this advice 🀍

Collapse
 
bop profile image
bop

github.com/gvergnaud/ts-pattern

this is also a good alternative

Collapse
 
abdoseadaa profile image
abdelrahman seada

will try it thanks πŸ’•

Collapse
 
alexmorgun profile image
Alexander Morgun

As always, all gold is in comments :)

Collapse
 
abdulrhmanmoha profile image
abdulrhman-moh

this is awesome

Collapse
 
abdoseadaa profile image
abdelrahman seada

you are awesome

Collapse
 
kookakoora profile image
KookaKoora

Amazing tip!

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks <3

Collapse
 
mohammed_chriatt_6865745c profile image
Mohammed CHRIATT

Thank you πŸ™

Collapse
 
abdoseadaa profile image
abdelrahman seada

You're welcome πŸ’•

Collapse
 
threestarss profile image
threestarss • Edited

There is nothing wrong with conditions, you just reshaped the data you are working with

Collapse
 
abdoseadaa profile image
abdelrahman seada

exactly, there is nothing wrong with conditions anyways , it's just a better approach

Collapse
 
tinashe_gunda_697ed0ca338 profile image
Tinashe Gunda

Well executed!

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks 🀍

Collapse
 
ehsansafari profile image
Ehsan Safari

You are doing great

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks πŸ’•

Collapse
 
abdoseadaa profile image
abdelrahman seada • Edited

didn't expect that anyone would see this post
cat meme

Collapse
 
mxteusg profile image
Mateus Guedes

Nice one!!!

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks :)

Collapse
 
dasezo profile image
Mohammed BENGUEZZOU

Brilliant <3

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks 🀍

Collapse
 
ronakkhunt profile image
Ronak Khunt

Well explained!

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks 🀍

Collapse
 
officialphaqwasi profile image
Isaac Klutse

very understandable.

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks 🀍πŸ”₯

Collapse
 
kkw855 profile image
KEY UNG KIM

thanks πŸ‘Œ

Collapse
 
abdoseadaa profile image
abdelrahman seada

you are welcome 😌🀍

Collapse
 
alyouma_akmal_5a4d549d061 profile image
alyouma akmal

Nice code

Collapse
 
abdoseadaa profile image
abdelrahman seada

thanks 🀍