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

前端 未结 9 1327
夕颜
夕颜 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:28

    Two things that may be relevant:

    Many projects use some convention where they set a global SERVER or CLIENT boolean so all your code can switch based off it. In your server bundle, set some global, like in this project

    global.__SERVER__ = true;
    

    And in your client bundle, set some global client to true, which you can achieve one way with Webpack's DefinePlugin

    new webpack.DefinePlugin({
      __CLIENT__: true
    })
    

    With the above approach, you could switch based off that variable in willMount, or render, to do one thing on the server, and another on the client.

    The second thing that may be helpful here is componentDidMount only runs on the client, but not on the server.

提交回复
热议问题