Skip to main content

If Directive

This example shows you how to conditionally render a component based on a prop. An $if directive is implemented in this example, which skips rendering a component if it's falsy.

function ifDirectiveMiddleware(next, type, props, key) {
if ('$if' in props) {
if (!props.$if) return null;
const { $if, ...rest } = props;
props = rest;
}

return next(type, props, key);
}

addMiddlewares(ifDirectiveMiddleware);

Usage

function App() {
const [show, setShow] = useState(false);

return (
<div>
<button onClick={() => setShow(!show)}>Toggle</button>

<div $if={show}>Show 'em</div>
</div>
);
}
http://localhost:3000

Typescript types

declare module 'react' {
interface Attributes {
$if?: any;
}
}