Pinwheeler Pinwheeler - 4 months ago 18
Javascript Question

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

Answer

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;