TypeError: Cannot read property userAgent of undefined
I am trying to integrate a responsive slider into my ReactJS app.
Its working as expected when I integrate it into a new demo app, but if I integrate it into my app it throws an error. I am using rails as backend.
When I try to import the slider into a component like
var Slider = require('react-slick');
it shows me the error.
error logs (in rails)
| ExecJS::ProgramError - TypeError: Cannot read property 'userAgent' of undefined:| execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:98:in `wrap_error'| execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:15:in `rescue in block in initialize'| execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:12:in `block in initialize' | execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:75:in `block in lock'| execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:73:in `lock'| execjs (2.7.0)
lib/execjs/ruby_racer_runtime.rb:9:in `initialize'| execjs (2.7.0)
Edit
Some where else in my code i wrote below code and it works fine
'use strict';
var React = require('react');
import logo from 'img/spark-logo.jpg'
var Carousel = require('nuka-carousel');
//import { NukaDecorate } from 'nuka-carousel-autoscroll';
class App1 extends React.Component{
// mixins: [Carousel.ControllerMixin],
render() {
return (
<Carousel>
<img src={logo} alt="Smiley face" />
<img src="http://placehold.it/1000x400/ffffff/c0392b/&text=slide2"/>
<img src="http://placehold.it/1000x400/ffffff/c0392b/&text=slide3"/>
</Carousel>
)
}
}
module.exports = App1;
source to share
The problem is that you are apparently trying to render your side of the application server (or at least you need it in a non-browser context).
One of the dependencies is trying to access a property on a userAgent
global object navigator
that is only defined in browsers.
To avoid this problem, you can try to isolate the plugin by only requiring it in the browser with a validation window
or ruby โโequivalent.
You can also just mock the variable for its default value, so it doesn't crash. Just define it as:
global.navigator = {
userAgent: 'node',
}
source to share