Pavel
Pavel

Reputation: 1974

ReactJS: Uncaught ReferenceError: require is not defined

I'm trying to use DRY in React JS. I'm trying to use the same HTML partial in different files

partial:

var AdminMenu = React.createClass({
 getInitialState: function() {
   return {};
 },
 render: function() {
   return (
     <h1>Menu</h1>
   );
 }
});

I'm requeiring it in another file:

require('./scripts/adminMenu.js');

ReactDOM.render(
 <AdminMenu/>,
 document.getElementById('content')
);

But I'm getting an error:

Uncaught ReferenceError: require is not defined

this scripts are included on html page like: <script type="text/babel" src="scripts/admin.js"></script>

I'm using webpack

Upvotes: 18

Views: 56275

Answers (4)

Bakul Gadara
Bakul Gadara

Reputation: 131

You have to use

const { Component } = React;
const { render } = ReactDOM;

in place of

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

Upvotes: 13

Sergey Belousov
Sergey Belousov

Reputation: 180

If you are not using any module bundler like webpack or etc. You should assign you components to some javascript global object, because objects from .jsx are not put in global scope

So here is the solution (used window object here)

Defined module:

window.AdminMenu = React.createClass({
  getInitialState: function() {
    return {};
  },
  render: function() {
    return (
      <h1>Menu</h1>
    );
  }
});

Where you use it:

ReactDOM.render(
  <window.AdminMenu/>,
  document.getElementById('content')
);

Upvotes: 11

steppefox
steppefox

Reputation: 1844

You should read more about modules for example here: https://www.sitepoint.com/understanding-es6-modules/

The main problems in your existing code are:

  1. It looks, in spite of that you are using Webpack, you use it wrong way. In your final bundle (final JS file), it shouldn't contain any 'require' keywords. Did you use Babel with your webpack? Please, show us your WebPack config.
  2. Your AdminMenu file looks not like module. Your adminMenu file should contain 'export' keyword, after that you will be able to 'require' or 'import' it from other files.

Also, you can write questions in comments with Russian if it is more convenient for you

Upvotes: 2

webdeb
webdeb

Reputation: 13211

Consider to use ES6 modules instead of require with React

export a module:

// src/hello.js
// export as default
export default const hello = ({name}) => (
  <h1>Hello {name}</h1>
)

import a module:

// src/index.js
// import from relative directory (src)
import Hello from './hello'

const App = () => {
  return (
    <div>
      <Hello name="Pavel" />
    </div>
  )
}

Upvotes: 2

Related Questions