DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,864 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Pavan K Jadda
Pavan K Jadda

Posted on • Updated on

ngIf(Angular) and v-if (Vue) alternative in React

In Angular or Vue, you can render components conditionally using directives like ngIf and v-if. But in React there is no concept of directives, you have to render components using below syntax

  return (
    <>
      {loading ? <></> : <EmployeeList/>} logged in.
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

However if you have nested conditions, then the template looks messy and very hard to read.

We can achieve the similar behavior in react with ReactIf component.

ReactIf.tsx

export default function ReactIf(props: { condition: boolean | undefined; children: React.ReactNode }): JSX.Element {
    return props.condition === undefined || !props.condition ? <></> : <>{props.children}</>;
}

Enter fullscreen mode Exit fullscreen mode

It is a functional component that accepts two properties

  1. condition
  2. children

condition: The condition on which component renders the passed children.
children: The Children to be rendered based on condition

You can rewrite our previous component as below, which is more readable

<ReactIf condition={loading}>
   <EmployeeList/>
</ReactIf>
Enter fullscreen mode Exit fullscreen mode

Happy Coding :)

Top comments (2)

Collapse
 
mattdevio profile image
Matt G

Its jsx so something like this

<div>
   {someValue === 3 && (
       <p>someValue is 3</p>
   )}
</div>
Enter fullscreen mode Exit fullscreen mode

react-cn.github.io/react/tips/if-e...

Collapse
 
pavankjadda profile image
Pavan K Jadda Author

Yep, I accidentally published the post without finishing. See the updated post now

Visualizing Promises and Async/Await ๐Ÿคฏ

async await

โ˜๏ธ Check out this all-time classic DEV post