Skip to content
← Snippets

Conditional Rendering

Trick for writing cleaner conditional rendering

Sep 3, 2022 · 1 min read

RenderIf.tsx
type Props = {
  children: React.ReactNode;
  isTrue: boolean;
};
 
export const RenderIf = ({ children, isTrue }: Props) => {
  return <>{isTrue ? children : null}</>;
};

Usage

import { useState } from 'react';
import { RenderIf } from '@/components/RenderIf';
 
function App() {
  const [value, setValue] = useState(4);
 
  return (
    <>
      <p>Current value: {value}</p>
      <RenderIf isTrue={value === 4}>
        <h1>Value is 4! I will rendered</h1>
      </RenderIf>
    </>
  );
}
Conditional Rendering | Viren Soni | Software Engineer