Sometimes, when using React libraries, such as react-router, I get this error:
Uncaught TypeError: Cannot read property \'firstChild\' of undefined
It seems to me peerDependencies is not getting traction. See https://github.com/npm/npm/issues/5080#issuecomment-40545599
I am maintaining react-date-picker (and other react modules), and what I've done until now is to specify the React dependency using the caret, for example ^0.12.0.
Also, when doing a build will all concatenated files, for use outside of the npm ecosystem, I use webpack with
externals: { 'react': 'React'}
which will look for the global var React
.
Using require('react')
and require('React')
inconsistently causes this problem as well, even if you only have one version of React.
https://www.npmjs.com/package/gulp-browserify didn't have this problem. Once I stopped using gulp-browserify and switched to watchify+browserify, Uncaught TypeError: Cannot read property 'firstChild' of undefined
started happening.
This error is commonly caused by two versions of React loaded alongside.
For example, if you npm install
a package that requires a different React version and puts it into dependencies
instead of peerDependencies
, it might install a separate React into node_modules/<some library using React>/node_modules/react
.
Two different Reacts won't play nicely together (at least yet).
To fix it, just delete node_modules/<some library using React>/node_modules/react
.
If you see a library putting React in dependencies
instead of peerDependencies
, file an issue.
For me, the problem was that I was using a <Link>
from react-router inside a <NavItem>
from react-bootstrap.
In case anyone has this issue having npm link
ed two modules depending on react, I found a solution...
Let's say you have Parent depending on React, and Child depending on react. When you do:
cd ../child
npm link
cd ../parent
npm link child
This causes this problem, because parent and child will each load their own instance of React.
The way to fix this is as follows:
cd parent
cd node_modules/react
npm link
cd ../../../child
npm link react
This ensures your parent project supplies the react dependency, even when linked, which is how npm would resolve the dependency when you are unlinked.
If you are experiencing this crash while server side rendering and none of these answers are the problem, here's the likely culprit:
Doing something async (setTimeout, AJAX, etc.) in componentWillMount. Since componentWillMount is called on the server, this setTimeout/request will still fire. If you setState inside this callback then it'll cause the error above.