Pinwheeler
Pinwheeler

Reputation: 1111

Require class from another file in ReactJS

I have a generic "main.js" and I want to get a class from another file. Here's what I have so far

Structure

main.js
/js
  /src
    menu.js

main.js

// main.js
var React = require('react');
var ReactDOM = require('react-dom');
require('./js/src/menu.js');

function run() {
    ReactDOM.render(React.createElement(Menu), document.getElementById('menu'));
}

var loadedStates = ['complete', 'loaded', 'interactive'];

if (loadedStates.includes(document.readyState) && document.body) {
  run();
} else {
  window.addEventListener('DOMContentLoaded', run, false);
}

menu.js (Edited for brevity)

//menu.js
var React = require('react');
var ReactDOM = require('react-dom');

var Menu = React.createClass({
    render: function() {
        //do things
    }
});

Unfortunately, at the end of it all, I get Uncaught ReferenceError: Menu is not defined

I'm using browserify to compile(?) everything into a bundle.js elsewhere in the project structure

Upvotes: 1

Views: 10531

Answers (2)

Vishwanath
Vishwanath

Reputation: 6004

You need to store required menu.js object in a variable and in menu.js export its object so that other modules can access it.

in main.js

var Menu = require('./js/src/menu.js');

and in menu.js at the end of file.

module.exports = Menu;

Upvotes: 6

elclanrs
elclanrs

Reputation: 94121

You have to export what you want to require:

// menu.js
module.exports = Menu;

// main.js
// This path should be relative to the current file
var Menu = require('./js/src/menu.js');

Upvotes: 2

Related Questions