reactjs,require,fs , ReactJS errors with rendering basic html component via variable

ReactJS errors with rendering basic html component via variable


Tag: reactjs,require,fs

I am trying to pass a string for the jsx template name to a component that will be responsible for just rendering basic html only components with no interaction (we have a lot).

'use strict';

import React from 'react';

export default class TemplateLoader extends React.Component {
  displayName = 'TemplateLoader'

  constructor(props) {

  render() {
    var template = require('./static-templates/'+this.props.template+'.jsx');
    return template(this);

and the output in the console is

Module parse failed: /Users/xxx/Sites/xxx/app/components/template-loader/static-templates/c017-top-phones-reasons.jsx Line 1: Unexpected token <
You may need an appropriate loader to handle this file type.
| <div class="xxx">
| </div>;
 @ ./app/components/template-loader/static-templates ^\.\/.*\.jsx$

If I switch it to

'use strict';

import React from 'react';
import jsx from 'react-jsx';
import fs from 'fs';

export default class TemplateLoader extends React.Component {
  displayName = 'TemplateLoader'

  constructor(props) {

  render() {
    var file = fs.readFileSync('./static-templates/'+this.props.template+'.jsx');
    var template = jsx.server(file, 'utf-8');
    return template(this);

I get

Error: ENOENT, no such file or directory './static-templates/xxx.jsx'
    at Object.fs.openSync (fs.js:438:18)
    at Object.fs.readFileSync (fs.js:289:15)

As commented below my set out is web pack, we're using Splash Pages for as a base. I've added html-loader, file-loader, css-loader.

My config for files has

node: {
  fs: "empty"
module: {
  loaders: [
    { test: /\.html$/, loader: "html-loader" },
    { test: /\.(jpe?g|png|gif|svg|eot|woff|ttf)$/, loader: 'file-loader' },
    { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader'] },
    { test: /\.json$/, exclude: /node_modules/, loader: 'json-loader' },
    { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' },
    { test: /\.css$/, loader: 'style-loader!css-loader' },


1. Enable Compilation of .jsx files

Inform Webpack use babel-loader when it encounters files ending in .jsx. See

So either add the following to your list of loaders:

'{ test: /\.jsx$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader'] },'

or modify your existing test so that it catches both .js and .jsx:

{ test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader'] },
              \- add x? here

Here, the ? mark operator in the test regular expression says "zero or one", so it captures both .js and .jsx.

2. Write your required modules according to CommonJS conventions

This won't work when you require it, because nothing is being exported. Everything in a CommonJS module is private to that module by default, you have to explicitly export whatever you want the caller of require to receive. So this will not work:

<div class="panel">


Instead, export the JSX expression:

module.exports = <div className="panel">
    I am static template 2!


Remember that in JSX, you're not using straight HTML. You need to use className rather than class. See for a list of other differences with "plain" HTML.

3. Make it work with React tooling

Now that you template is found, loaded, and compiled, it still won't render. You'll get this error: Uncaught ReferenceError: React is not defined or something like it. Let's take a look at the JavaScript that is generated by the babel-loader, which transforms JSX into plain old JavaScript:

"use strict";

module.exports = React.createElement(  // <-- error here
  { className: "panel" },
  "I am a static template 2!"

So the output of the JSX transform expects React to be in scope. This makes sense because JSX is just a convenience syntax for writing React.createElement(.... So finally, to make it all work together, your template needs to look like this:

import React from 'react';
// or var React = require('react');

module.exports = <div className="panel">
    I am a static template 2!

Caveat: I did not try to get this working with react-hot-loader directly, but it does work under webpack-dev-server, which I believe uses react-hot-loader. So this should work, but it it doesn't try removing react-hot-loader.

My working implementation looks like this. Note that I pass in the template as a prop rather than computing it within the component. I think this is more idiomatic React. Also this uses some new ES6 syntax for fun, but you're using babel so it should be okay. Not exactly what you are doing but close. One thing to note, it's probably better to call require once (in the constructor or in componentDidMount) rather than in the render function which can be called quite frequently.

var StaticTemplateComponent = React.createClass({
    render: function () {
        return this.props.template;

window.mountStaticComponent = (templateName, element) => {
    var templatePath = `./static-templates/${templateName}.jsx`;
    var template = require(templatePath);

    var staticTemplateComponent = React.createElement(StaticTemplateComponent, {template: template});
    React.render(staticTemplateComponent, element);

4. Automatically wrap your static templates in the required CommonJS

Out of scope for the question, and left as an exercise to the reader. It should be possible to write a custom webpack loader that automatically wraps your templates in the appropriate import/export statements. Bonus points for automatically transforming HTML5 into compliant JSX.

As far as why it doesn't work with jsx.server, I've never used it. Based on the error I would guess it's looking in the wrong directory for your files, so again, probably a configuration issue.


Using the shell provided with NodeJS

Once you've installed NodeJS, you'll have a executable in your computer named NodeJS which is a shell. I was wondering what can I do with that... here you're able to run JS code as, for example, in the browser's console, great. Now, is it possible to require modules in that...

Should every object in the store state be immutable?

I am learning React.js and Flux, and I understand that is better to keep the object immutable because comparing them is O(1). My situation is this: I have a store, which has a _state object, that is a map (I'm using Immutable-js). That _state has some booleans, some strings and...

reactjs Uncaught TypeError: Cannot read property 'map' of undefined

I have used getInitialState on my BrowseWidgetBox component. Although when passing the data to my MainMenu component, the data remains empty, as if the AJAX call to the api was never run in the BrowseWidgetBox. My question then, is why is this happening? Shouldn't componentDidMount call the ajax api and...

Nesting in Default Route

I have an applications index page that lists all my applications. The index page is also the default route. I want to nest a 'applications new' modal in the index page. This way I can render the modal while on top of the index page. However, I'm not able to...

After scrolling on IPad, some content of my website is hidden behind a white area

Introduction We're developing a website and on one page we'd like to display some simple charts. Therefore we're using canvas to draw the charts. I konw there are other great libraries therefore, but right know we just need a quick and dirty solution for a first shot. Generally we work...

Should I pass all the state in every change from store to component?

I am new on React and Flux and I am making an app that will have an input (like the name or the title), and below a list of n things. How should I handle the event listeners? I saw in the TODO example of flux ( that they use...

Input validation setTimeout in ReactJS

I have a component that renders with className="error" or classname="" depending on whether the input is valid or not. This way in CSS I can simply do .error { background: red; }. The validity of the input is determined by the isValidNumber(..) function. However, right now the problem I'm having...

ReactJs - Using Mixins with ES6

Following up on's video - 'React Components in ES 6 classes', the below works: 'use strict'; import React from 'react'; import Button from './components/form/button'; import Label from './components/form/label'; // after refactoring //import ReactMixin from './super-classes/react-mixin'; //ToDo: Reactor below let reactMixin = InnerComponent => class extends React.Component { constructor() {...

No call function of parent in Reactjs

I have two function in Reactjs. When function one call a function of function two. There have error same as "Uncaught TypeError: this.props.onButonShowClick is not a function" This is function one : var HiddenEdit = React.createClass({ _handleOnClick: function(e) { e.preventDefault(), this.props.onButonShowClick(true); }, render: function() { return (<span className="col-lg-2 btn-action-group"> <a...

Create CRUD UI in reactjs with backend api

Ive created a CRUD app in laravel, but now i want to improve the UI with react.js. Im still very new to react, so not sure how to go about doing this. So far i have created a table component that displays all the users with react. how should i...

checking for first key in map with reactjs

I've got the following component in ReactJS var MainMenu = React.createClass({ render: function() { console.log(this.props.groupsData); var categories ={ return (<li><a href="#">{obj.display_name}</a></li>); }); return (<div className="MainMenu"> <ul className="nav nav-pills">{categories}</ul> </div>); } }); Now, I wish to add className='active' to the <li> element if its the first in the map. How...

Unable to render second react component

I am just fiddling with react to make a simple website. So here's the code <html> <head> <script src=""></script> <!-- In-browser JSX transformer, remove when pre-compiling JSX. --> <script src=""></script> <link rel="stylesheet" href=""> </head> <body> <div class="container"></div> </body> <script type="text/jsx"> var...

Events not propagating across react components

I have the following react components: class Button extends React.Component { constructor(props){ super(props); this.state = { disabled: false }; } render() { return <button disabled={this.state.disabled} onClick={this.clicked.bind(this)}>Save</button>; } clicked(event) { this.setState({disabled: true}); } } class Form extends React.Component { contructor(props) { super(props); this.state = { foo: "bar" }; } render() {...

Dynamic className in cjsx

I am trying to hide a component and update the image in a button when I click said button. I have managed to hide the component by doing the follow: {<MyAwesomeComponent /> unless @state.hide} And I change the state by doing: toggleComponent = -> @setState hide: [email protected] . . ....

Reactjs this.state giving Uncaught TypeError: Cannot read property 'groupsData' of null

I am doing 2 basic ajax calls to 2 different apis in one of my ReactJs components. Although, when running the call (on urls I know for certain are working and returning data), I receive: Uncaught TypeError: Cannot read property 'groupsData' of null Here is the single component: var BrowseWidgetBox...

React from NPM cannot be used on the client because 'development' is not defined. The bundle was generated from Webpack

I'm creating a React Node.js app and I'm trying to generate a Webpack bundle containing the React source code I loaded from NPM. However, it seems that the React code from NPM cannot be used directly in the client. It triggers this error: Uncaught ReferenceError: development is not defined The...

Include, Require a syntax error file

I would like to ask can I require/include a file that has syntax errors and if I cant, the require/include returns a value so that I know that the required/included file has syntax errors and cannot be required/included ? file.php has syntax error include('file.php') if (not file.php included because of...

Reactjs - the spread operator giving error

I am trying to use the spread operator in react.js but getting the error Unexpected token ... in Chrome. I am getting an error at the line 3 in this code: var Btn=React.createClass({ render: function(){ var { className, ...other }=this.props; return (<a {...other} className={joinClasses(className,"btn")} href="#" >{this.props.children}</a>); } }); and using...

Why should addChangeListener be in componentDidMount instead of componentWillMount?

I saw this line as an answer to another question on here: "componentWillMount should be componentDidMount, or else you'll leak event emitters in node." and I don't really understand it. Can someone explain with more detail? More info: Building a react application with flux, as part of the initial render,...

JQuery .animate() not working with ReactJS?

I am trying to highlight a cell when the user click on it by using jQuery .animate() clickHandler: function() { var cell = React.findDOMNode(this.refs.cell); // $(cell).css("background-color", "blue"); // THIS WORK $(cell).animate({ backgroundColor: "blue" }, 1000); // THIS DOESN'T WORK }, I am also using React.addons.CSSTransitionGroup. Maybe there is a conflict...

Cart not adding correct item in React.js

I'm learning React.js (and I'm a beginner at JavaScript) and having some difficulty getting my addToCart function working properly. I've managed to get all my products to display but adding to cart on any of them only adds the first item, and once that item is out of stock then...

Dynamic key in immutability update helper for array

javascript,reactjs,ecmascript-6 I have an update function that receives an index along with the event so as to alter the value for that specific item in the array. How do I get index to be evaluated instead of treated as a set key in this scenario? Is it even possible? updateValue:...

difference between componentDidMount and getInitialState in Reactjs

I understand that getInitialState is called once in the component's lifecycle and componentDidMount is called when the component is rendered. So does that mean both will get called just once in the component's lifecycle? What's the difference?...

React js css transitions on class removal

I have column that should have different width depending on some flag. I use Bootstrap, so I assign col-xs-12 and col-xs-2 depending on the flag. Now I want it to change width slowly with css transition. I've read official React.js doc about transitions, but it doesn't apply to my case:...

How to access nested object in React js 0.13.3

The below added code is working fine in React js 0.10.0. I wanna run same code in 0.13.0 version also. My main requirement is accessing nested object as default object like "". <!doctype html> <html> <head> <title>Weather Widget</title> <link rel="stylesheet" href="weather.css" /> <script src=""></script> <script src=""></script> <script...

Canvas element does not resize when using ReactJS and PaperJS together

I have found that canvas elements correctly resize on window resize when they are inside react components. They also resize correctly when used with PaperJS. However, they do not resize when used with PaperJS and ReactJS together. Is this an incompatibility between PaperJS and ReactJS or am I instantiating PaperJS...

Better/faster way for changing React array state than cloning it?

Whenever a React class has a state object that is or contains an array, updating that state feels awkward. Usually what I do is var newArrayThing = _.clone(this.state.arrayThing); //or slice() newArrayThing[123] = 42; //update stuff this.setState({arrayThing: newArrayThing}); Is there a better or more elegant way of handling this I am...

Adding multiple divs or renders in ReactJs

I'm having trouble in wanting to create multiples of the same html that I render in a certain class. For example, I have a div that might look like this [Header goes here, is a input field] [Dropdown] [TextArea] [Submit] [Add another field] On add another field, I would like...

How do I set state of sibling components easily in React?

I have got the beginnings of a clickable list component that will serve to drive a select element. As you can see from the below, onClick of the ListItem, I'm passing the state of a child element (ListItem in this case) to the parents (SelectableList, and CustomSelect component). This is...

React page layout using react-router

I have a default layout page here using react router: Header = require('./components/Header'), Footer = require('./components/Footer'), var sampleApp= React.createClass({ getDefaultProps() { return { title: 'Page One' }; }, render: function (){ return ( <div className="app"> <Header title={this.props.title} /> <RouteHandler /> <Footer /> </div> ); }, }); var routes = (...

ReactJS passing a prop that the element owns to a function

I am trying to return a <li> element with an eventListener. But I want the <li> to pass a property it owns to a function onClick. This is specifically what I am talking about: return (<li onClick={this.changeTab(tab_id)} tab_id={index + 1} <a href="#">{obj.display_name}</a></li>); But if you do something like this, you...

how to render through a simple for-loop in Reactjs?

I have a simple react component defined below React.createClass({ generateContent:function(){ for(i = 1;i<=100;i++) if(i%2 == 0) { return <li>Even!</li> } else{ return <li>Odd!</li> } }, render:function(){ return (<ul> {this.generateContent()} </ul>) } }) While Rendering, The component returns the first statement of the for loop(<li>Odd</li>) and then exits. I'd like something...

html Forms inside reactJS

I used the (almost) exact syntax for creating an html form in react: var Hello = React.createClass({ render: function() { return <div> <section> <form action="http://localhost:9203/ask"> Text: <input type="text" name="text" value="Text"/> <br/> Focus: <input type="text" name="focus" value="Focus"/> <br/><br/> <input type="submit" value="Submit"/> </form> </section> </div>; } }); React.render(<Hello name="World" />, document.getElementById('container'));...

Expected corresponding JSX closing tag for input Reactjs

While creating a component in Reactjs with input fields error occurs Error: Parse Error: Line 47: Expected corresponding JSX closing tag for input at http://localhost/chat-react/src/script.js:47:20 </div> var Main = React.createClass({ render: function() { return ( <div className="card-action"> <i class="mdi-action-account-circle prefix"></i> <input id="icon_prefix" type="text" class="validate"> </div> ); } }); ...

How do I load SVGs directly in my React component using webpack?

I would like to render a material design icon directly in my NextButton component using webpack. Here's the relevant part of my code: var NextIcon = require('material-design-icons/navigation/svg/production/ic_chevron_right_18px.svg'); var NextButton = React.createClass({ render: function() { return ( <Link to={} className='button--next'> {this.props.label} {NextIcon} </Link> ) } }); But this isn't working as...

react-native this.setState not working

I know there's already a similar question but there's no code shared in there. Under navbarChanged() > if condition, I'm doing a this.setState. This is of type HomeTab but setState doesn't seem to be working. Any clues/pointers? class HomeTab extends React.Component { constructor() { super() this.setState({ isNavBarHidden: false }); }...

React Component with subcomponents or render HTML in parent?

I have a question regarding React patterns. When rendering a component, is it appropriate for this component to render several sub-components, or is it ok to render some HTML in the parent component. Example: If I have a box that has a heading and a body with list of elements,...

ReactJS code with and without class definitions: which one is preferred?

Structurally, how different are these two code? Aren't they (almost) equivalent? In what situations one is preferred over the other? var Hello = React.createClass({ render: function() { return ( <div>Hello World</div> ); } }); React.render(<Hello />, document.body); and class SampleApplication extends React.Component { render() { return ( <div>Hello World</div> );...

Page update when clicking a button (reactjs)

Suppose I want to render page again, after clicking a button. How can I accomplish it? In particular how would you change my program to generate random texts, when clicking the button? var colors = ['red', 'yellow', 'blue', 'green']; var Hello = React.createClass({ randomText(color) { var style = { color:...

Not able to access variables in required file

I'm using browserify on a project and am running in to the following: I have a file test.js. In test.js there is nothing but the following: var test = 'test'; Now, in the same directory I have my main file 'app.js'. I require test.js and try to access the 'test'...

What is the proper way to get the value of a React