I\'m building a isomorphic application, but I\'m using a third-party component that only renders on the client. So, particularly for this component, I need to only render it
You can use reacts lifecyle events (e.g.: componentDidMount) to detect server/client side rendering.
import { useState, useEffect } from 'react'
function useIsServer () {
const [isServer, setIsServer] = useState(true)
useEffect(() => {
setIsServer(false)
}, [])
return isServer
}
Usage
See below (Functional Component)
import useIsServer from './above'
function ServerOnly ({ children = null, onClient = null }) {
const isServer = useIsServer()
return isServer
? children
: onClient
}
Usage
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