Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'userAgent' of undefined

I am trying to integrate react-slick slider into my ReactJS application.

Its working as expected when I integrate it into a new demo app, but if I integrate it into my own application it throws an error. I am using rails as backend.

When I try to import slider in component like

 var Slider = require('react-slick'); 

it shows me an error.

error logs (in rails) are

| 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 have written below code and it's working 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; 
like image 293
Anish Avatar asked May 15 '17 04:05

Anish


1 Answers

The issue is that you are apparently trying to render your app server side (or at least it's required in a non-browser context).

One of the dependencies of is trying to access the userAgent property of the global navigator object, which is only defined in browsers.

To avoid this issue, you could try to isolate the plugin by only requiring it on the browser with a check on the window or equivalent in your ruby.

You can also simply mock the variable to a default value, so it doesn't crash. Simply define it like:

global.navigator = {
  userAgent: 'node',
}
like image 82
Preview Avatar answered Sep 22 '22 04:09

Preview