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()
.
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
Just a curiosity, why the !! at the beginning?
!!
casts the value to a boolean to make sure thattrue
orfalse
is returned instead of potentiallyundefined
. You could replace!!
above withBoolean
and get the same resultSince here we are using the
&&
operator I can't see a path that can eventually returns undefined, or other values other than true or false. Am I wrong?if
window.document
exists, but has nocreateElement
method, this will returnundefined
. If it does have acreateElement
method, it would return that method AKA a function. To test this, you can copy and paste it in your javascript console (without the!!
) and see that it returns a function