/

Conditionally render on the client or server

react
On this page
  • Usage
tsx
import React, { useEffect, useState, ReactNode } from 'react'
export interface ConditionallyRenderProps {
client?: boolean
server?: boolean
children?: ReactNode
}
const ConditionallyRender = ({
client,
server,
children,
}: ConditionallyRenderProps) => {
const [isMounted, setIsMounted] = useState(false)
useEffect(() => setIsMounted(true), [])
if (!isMounted && client) {
return null
}
if (isMounted && server) {
return null
}
return children as React.ReactElement
}
export default ConditionallyRender

Usage

tsx
<Layout>
<ConditionallyRender server>
<p>This is rendered only on server.</p>
</ConditionallyRender>
<ConditionallyRender client>
<p>This is rendered only on client.</p>
</ConditionallyRender>
</Layout>
Edit this page
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.