Get started with React and ES6

advertisements

I can find enough resources about getting started with React using ES5. How do I get started with React in ES6?

I would like:

  • Hot module reloading
  • A media query for responsive-web

1. Download Node.js

Get the latest stable version of Node.js

2. Install Necessary Packages

2.1. package.json

Copy and paste the following code:

{
    "name": "NewComponent", // Change me
    "version": "1.0.0",
    "author": "Me", // Change me
    "license": "ISC",
    "repository": {
        "type" : "git",
        "url" : "https://github.com/" // Change me
    },
    "readme": "Link To ReadMe Markdown File", // Change me
    "description": "This is where the magic happens", // Change me
    "main": "Main Module's Export Object", // Change me
    "dependencies": {
        "react": "^0.14.3",
        "react-dom": "^0.14.3",
        "react-responsive": "^1.0.1"
    },
    "devDependencies": {
        "babel": "^6.3.26",
        "babel-cli": "^6.3.17",
        "babel-core": "^6.3.21",
        "babel-eslint": "^4.1.4",
        "babel-polyfill": "^6.1.19",
        "babel-runtime": "^6.1.18",
        "babel-plugin-transform-runtime": "^6.1.18",
        "babel-preset-es2015": "^6.1.18",
        "babel-preset-react": "^6.1.18",
        "babel-preset-stage-0": "^6.1.18",
        "babel-preset-stage-1": "^6.1.18",
        "babel-preset-stage-2": "^6.1.18",
        "babel-preset-stage-3": "^6.1.18",
        "babel-loader": "^6.2.0",
        "file-loader": "^0.8.4",
        "json-loader": "^0.5.2",
        "express": "^4.13.3",
        "path": "^0.12.7",
        "webpack": "^1.12.1",
        "webpack-dev-server": "^1.14.1"
    },
    "scripts": {
        "dev-server": "webpack-dev-server --progress --colors --inline --config .//webpack.config.js",
        "author": "Me", // Change me
        "license": "ISC"
    }
}

Edit the lines that read, "Change me" and delete the "Change me" comments. If you wish to skip this for now, at the very least, delete the "Change me" comments. Navigate to a new project folder, and save this file as package.json in your project directory

2.2. Run Install Script

Navigate to your new project folder in the terminal and run: npm install

Node Package Manager will then install all of the packages in your package.json file to your project directory

3. Setup a Basic App

3.1. index.html

Save the following as index.html:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <style>
            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
            #container {
                display: block;
                height: 100%;
                width: 100%;
            }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="./bundle.js" charset="utf-8"></script>
    </body>
</html>

Take note of the container div. React needs an element to render it's components in.

3.2. webpack.config.js

Save the following as webpack.config.js:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: ['babel-polyfill', path.resolve(__dirname, "Application.js")],
    output: {
        path: path.resolve(__dirname, './'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
    exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
        plugins: ['transform-runtime'],
        presets: ['es2015', 'stage-0', 'stage-1', 'stage-2', 'stage-3', 'react'],
                }
            },
            {
    test: /\.json$/,
                loader: "json-loader"
            }
        ]
    }
};

This file is the configuration of Webpack, my module bundler of choice

3.3. Application.js

Save the following as Application.js:

import React from 'react';
import ReactDOM from 'react-dom';
import ComponentNameComponent from './ComponentNameComponent.js';

class Application extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <ComponentNameComponent />
        );
    }
}

ReactDOM.render(<Application />, document.getElementById('container'));

Use the replace feature of your text editor to replace "ComponentName" with what you want to call your component. Three times it should read [ComponentName]Component.js

3.4. [ComponentName]Component.js

Save the following as the name of your component plus the word "Component" at the end:

import React from 'react';
import ReactDOM from 'react-dom';
import MediaQuery from 'react-responsive';
import ComponentName from './ComponentName.js';

class ComponentNameComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <MediaQuery minWidth={960}>
                    <ComponentName display="desktop" />
                </MediaQuery>
                <MediaQuery maxWidth={959}>
                    <MediaQuery minWidth={1}>
                        <ComponentName display="mobile" />
                    </MediaQuery>
                    <MediaQuery maxWidth={0}>
                        <div></div>
                    </MediaQuery>
                </MediaQuery>
            </div>
        );
    }
}

export default ComponentNameComponent;

Use the replace feature of your text editor to replace "ComponentName" with what you want to call your component. In the render() function, there is a media query and depending on the screen size, the component is passed a parameter called display with one of two values: "desktop" or "mobile"

3.5. [ComponentName].js

Save the following as your component's name:

import React from 'react';
import ReactDOM from 'react-dom';

class ComponentName extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        // CSS Here
        var spanStyle = {
            fontSize: '24px',
            fontFamily: 'geneva, roboto, sans-serif'
        };
        if (this.props.display == 'desktop') {
            // CSS can also go here if desktop specific
            return (
                <div>
                    {/* React Components and HTML Here for desktop display */}
                    <span style={spanStyle}>Welcome to React. Resize the browser window to a small width.</span>
                </div>
            );
        }
        else {
            // CSS can also go here if mobile specific
            return (
                <div>
                    {/* React Components and HTML Here for mobile display */}
                    <span style={spanStyle}>Hi, I am the mobile view. Welcome to React. Resize me back!</span>
                </div>
            );
        }
    }

    componentDidMount() {
        // Only acceptable place to use window and document objects
    }
}

export default ComponentName;

To edit your app from here on out, do not edit the Application.js or ComponentNameComponent.js classes. Instead consider the ComponentName.js class your new top-level class.

The Application.js is only used for development. If you want to re-use your component in another application, you should import the ComponentNameComponent.js class (see the "Making Apps Fast" link below for information on why you want container classes). Adding extra code to the ComponentNameComponent.js class might cause unintended effects in the media query.

3.6. Run Your App

Go to your project in your terminal and run the following script:

npm run dev-server

4. Think in React

Think in React

React.JS Conference 2015 - Making Apps Fast

This is just a start. I hope this helped. The original reason for writing was a Wiki article for my job. I would like to refine this so please comment on what you liked or what you found confusing.