In React, how do I detect if my component is rende

2020-02-26 03:00发布

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 when I'm rendering in the client.

How do I detect if I'm at the client or at the server? I'm looking for something like isClient() or isServer().

8条回答
走好不送
2楼-- · 2020-02-26 03:29

You could also just use the use-ssr React hook

import useSSR from 'use-ssr'

const App = () => {
  var { isBrowser, isServer } = useSSR()

  // Want array destructuring? You can do that too!
  var [isBrowser, isServer] = useSSR()

  /*
   * In your browser's chrome devtools console you should see
   * > IS BROWSER:                                                                     
查看更多
Rolldiameter
3楼-- · 2020-02-26 03:30

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'
/>
查看更多
欢心
4楼-- · 2020-02-26 03:30

You can check if global window variable is defined or not. as in browser it should always be defined.

var isBrowser = window!==undefined
查看更多
来,给爷笑一个
5楼-- · 2020-02-26 03:34

Internally, React uses a utility called ExecutionEnvironment for this. It implements a few useful properties like canUseDOM and canUseEventListeners. The solution is essentially just what's suggested here though.

The implementation of canUseDOM

var canUseDOM = !!(
  (typeof window !== 'undefined' &&
  window.document && window.document.createElement)
);

I use this in my application like this

var ExecutionEnvironment = require('react/node_modules/fbjs/lib/ExecutionEnvironment');
...
render() {
  <div>{ ExecutionEnvironment.canUseDOM ? this.renderMyComponent() : null }</div>
}

EDIT This is an undocumented feature that shouldn't be used directly. Its location will likely change from version to version. I shared this as a way of saying "this is the best you can do" by showing what the Facebook team uses internally. You may want to copy this code (it's tiny) into your own project, so you don't have to worry about keeping up with its location from version to version or potential breaking changes.

ANOTHER EDIT Someone created an npm package for this code. I suggest using that.

npm install exenv --save
查看更多
▲ chillily
6楼-- · 2020-02-26 03:39

You can also use componentDidMount(), as this lifecycle method is not run when the page is server-side rendered.

查看更多
不美不萌又怎样
7楼-- · 2020-02-26 03:40

You can create one useful utility with the help of the exenv package.

import { canUseDOM } from 'exenv';

export function onClient(fn: (..._args: any[]) => any): (..._args: any[]) => any {
    if (canUseDOM) {
        return fn;
    }

    if (process.env.NODE_ENV === 'development') {
        console.log(`Called ${fn.name} on client side only`);
    }

    return (): void => {};
}

And use it like this

function my_function_for_browser_only(arg1: number, arg2: string) {}

onClient(my_function_for_browser_only)(123, "Hi !");

And the function will only be called on client side, and it will log on server side that this function has been called on client side if you set NODE_ENV=development

(It's typescript, remove types for JS :) )

查看更多
登录 后发表回答