简体   繁体   中英

React isomorphic inconvenience

I'm building isomorphic app using Node.js and ReactJS .

I've met a situation when inside some isomorphic React component (rendered both on client and server sides) I need to include only client-side dependency (some notifications library for example).

What is the best way to have it worked (compiled) both on server/client sides?

PS: I have few thoughts about possible workarounds something like checking for browser env variables (ex. some typeof window !== 'undefined' ) etc. but I'm not sure it's a good way to go.

Use the lifecycle method componentDidMount which is not invoked on the server instead of checking if window is undefined.

The "downside" is if your client side dependency enhances an element for example or changes any property of it, it'll get the default property first since it was rendered server side and when componentDidMount runs it'll get changed causing a "blink".

If you are using browserify I often use process.browser which is only true in browserified code.

If you wanted to get fancy and remove server code from the browser instead there is also isbrowser which will do just that.

Another way (webpack or browserify) is to take advantage of the browser field in the package.json. You can make it so that the server requires a noop file and the browser requires a file the exposes the client side api.

I have defined variable in webpack configuration file called process.env.WEBPACK and in my code when i need something like bottstrap js or something else i just write

  if(process.env.WEBPACK){
     //awesome lib included or scss or whatever
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM