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

Pavan Jadda
1 min readSep 11, 2022

--

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

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

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>

Happy Coding :)

--

--