Pinwheeler Pinwheeler - 9 months ago 44
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




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

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

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

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

menu.js (Edited for brevity)

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


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;