home.


Tagged: reactjs


Reactjs: Quick start tutorial for react-router with browser history

Let’s first initialise our directory and install the modules. I’m using nodejs v5.10.1.

mkdir our_dir && cd our_dir
mkdir src
npm init -y
npm install react react-dom react-router --save
npm install webpack babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev

Now let’s use a webpack.config.js that uses an entry point of src/router.js and outputs to bundle.js using the babel loader with es2015 and react presets:

module.exports = {
        entry: "./src/router.js",
        output: {
                path: __dirname,
                filename: "bundle.js"
        },
        module: {
                loaders: [
                        { loader: 'babel', query: { presets: ['es2015', 'react'] }, exclude: /node_modules|bower_components/ }
                ]
        }
};

The first files in our src directory will simple components that output some simple text. pageone.js:

import React from 'react'
import { render } from 'react-dom'

const Pageone = React.createClass({
  render: function() {
    return <div>This is page one</div>;
  }
});

export default Pageone;

pagetwo.js:

import React from 'react'
import { render } from 'react-dom'

const Pagetwo = React.createClass({
  render: function() {
    return <div>This is page two</div>;
  }
});

export default Pagetwo;

The next component will be the main layout. We’ll call it mainlayout.js. It uses the Link component from react-router to create links. The {this.props.children} part will be replaced with the components to which we will navigate.

import React from 'react'
import { render } from 'react-dom'
import { Link } from 'react-router'

const MainLayout = React.createClass({
  render() {
    return (
      <div>
        <Link to="/pageone">Page one</Link> | <Link to="/pagetwo">Page two</Link>
        {this.props.children}
      </div>
    )
  }
})

export default MainLayout;

The next file router.js, which we refer to in our webpack.config.js file, is where we import all our components and define the route:

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'

import MainLayout from './mainlayout';
import Pageone from './pageone';
import Pagetwo from './pagetwo';

render((
  <Router history={hashHistory}>
    <Route path="/" component={MainLayout}>
      <Route path="pageone" component={Pageone} />
      <Route path="pagetwo" component={Pagetwo} />
    </Route>
  </Router>
), document.getElementById('container'));

We use the Router tag to start the routes, specifying {hashHistory}, which we imported, to tell react-router how to deal with history.

Within such, we have a Route which has a path attribute, which is just the root, and a component attribute, which is the MainLayout component we defined earlier.

Without that, we define two routes, named pageone and pagetwo, which relate to the link names in MainLayout. And we set the components to the ones we defined above.

And we render all that in to a container id which we will create in our index.html file.

Now go back into the main directory, and create this simple index.html file, with the container id relating to the above router.js file, and the bundle.js relating to the file webpack will shortly create for us.

<div id="container"> </div>
<script src="bundle.js"></script>

Finally, webpack to create the bundle.js file:

./node_modules/webpack/bin/webpack.js

which should output something like:

Hash: 4aeabfc523370b2c0c2c
Version: webpack 1.13.0
Time: 1246ms
    Asset    Size  Chunks             Chunk Names
bundle.js  858 kB       0  [emitted]  main
    + 228 hidden modules

And now if you visit your index.html file on your web server, you should see the router in action, complete with browser history.

The first page will just be what we defined in our MainLayout. If you want a default component there, use <IndexRoute component={Index} /> within your Route and create the Index component.

reactjs react-router

Using Webpack with babel and reactjs

If you’re using webpack–and you probably are–with react, you can set webpack to process all the javascript files with babel, converting all the es2015 and reactjs stuff ready for the web.

The following converts everything, including the es2015 modules, from src/app.js to bundle.js, using the babel loader, with es2015 and react presets.

module.exports = {
        entry: "./src/app.js",
        output: {
                path: __dirname,
                filename: "bundle.js"
        },
        module: {
                loaders: [
                        { loader: 'babel', query: { presets: ['es2015', 'react'] } }
                ]
        }
};

The above should be your webpack.config.js file

The npm modules you need are:

npm install webpack
npm install babel-loader babel-core babel-preset-es2015 --save-dev
reactjs webpack

Webpack: Quick introduction

The wonders, or horrors, of the reactjs toolchain generally includes webpack.

First off, on ubuntu, ensure you’re on the latest node:

curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash
sudo apt-get install -y nodejs

Afer you’ve initialised your package.json with npm init -y or similar, install webpack and its css and style loader.

npm install webpack
npm install css-loader style-loader

Now let’s have an entry.js file that will be included in our ‘pack’

require("./style.css");
document.write(require("./content.js"));

The first line includes a css file, and the second writes out content that is included in the module export of the content.js file.

Here’s the style.css file:

body {
    background: yellow;
}

And here’s the content.js file

module.exports = "It works from content.js.";

Now to actually bundle this up, you need to call webpack as thus:

node_modules/webpack/bin/webpack.js ./entry.js bundle.js --module-bind 'css=style!css'

This defines all files with .css use the css-loader module we installed above, and bundles everything in entry.js into bundle.js

But you probably want all the command line stuff in a config file, the webpack.config.js file as default:

module.exports = {
        entry: "./entry.js",
        output: {
                path: __dirname,
                filename: "bundle.js"
        },
        module: {
                loaders: [
                        { test: /\.css$/, loader: "style!css" }
                ]
        }
};
webpack reactjs

ReactJs: Precompiling JSX babel files

When you use JSX/Babel in your reactjs app, the import for babel is rather large.

You can, instead, precompile the files from babeljs to javascript using the babel-cli application.

First install babel-cli and its presets using npm:

npm init -y
npm install --save-dev babel-cli
npm install --save-dev babel-preset-es2015 babel-preset-react

Then ensure your have both src and dist directories, and put the JSX/Babel files in the src directory.

Now we can run the babel cli program to automatically convert babel files to javascript file in the dist directory:

nodejs node_modules/babel-cli/bin/babel.js --presets es2015,react --watch src --out-dir dist

Now you can remove the script import for babel, and change the paths to the components to the dist/ directory:

Your index.html:

<script src="bower_components/react/react.min.js"></script>
<script src="bower_components/react/react-dom.min.js"></script>

<div id="container"> </div>

<script src="dist/helloworld.js"></script>

And now the helloworld.js (in the src directory, not in the dist directory which is generated):

var Hello = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

ReactDOM.render(
  <Hello name="Jim" />,
  document.getElementById('container')
);
reactjs babeljs

ReactJS: Getting started with a component very quickly and simply

First let’s install babel and reactjs using bower:

bower install --save babel
bower install --save react

Create an index file as such, in your HTML directory served from someplace:

<script src="bower_components/react/react.js"></script>
<script src="bower_components/react/react-dom.js"></script>
<script src="bower_components/babel/browser.min.js"></script>
<script type="text/babel" src="helloworld.js"></script>

<div id="container"> </div>

This loads in the reactjs and babel stuff, a local file called helloworld.js in the babel format, which we’ll look at next, and then defines a placeholder for a container.

Now the helloworld.js babel file is as so:

var Hello = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

ReactDOM.render(
  <Hello name="Jim" />,
  document.getElementById('container')
);

It creates a react component called ‘Hello’, which returns some HTML in its render function, using a property passed to the component.

The next part renders the component, passing in “Jim” as the name property, and specifies the component in index.html to render to, ‘container’ in our case.

reactjs reactjs-components

Page 1 of 1