In React, how do I detect if my component is rendering from the client or the server?

前端 未结 9 1329
夕颜
夕颜 2020-12-29 18:41

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

9条回答
  •  情深已故
    2020-12-29 19:41

    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

    
    

    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

    
    

提交回复
热议问题