You can use reacts lifecyle events (e.g.: componentDidMount
) to detect server/client side rendering.
Examples
As Hook
import { useState, useEffect } from 'react'
function useIsServer () {
const [isServer, setIsServer] = useState(true)
useEffect(() => {
setIsServer(false)
}, [])
return isServer
}
Usage
See below (Functional Component)
As Functional Component
import useIsServer from './above'
function ServerOnly ({ children = null, onClient = null }) {
const isServer = useIsServer()
return isServer
? children
: onClient
}
Usage
<ServerOnly
children='This String was rendered on the server'
onClient='This String was rendered on the client'
/>
As Class Component
class ServerOnly extends React.Component {
constructor (props) {
super(props)
this.state = {
isServer: true
}
}
componentDidMount() {
this.setState({
isServer: false
})
}
render () {
const { isServer } = this.state
const { children, onClient } = this.props
return isServer
? children
: onClient
}
}
Usage
<ServerOnly
children='This String was rendered on the server'
onClient='This String was rendered on the client'
/>