Cell PhonesComputersConsumer ElectronicsGraphic Design & Video EditingHome Theater & AudioIndustrial TechnologyInternet

Getting Started With ReactJS and Web API 2 From Scratch!

Updated on February 11, 2017

What Tool are Needed?

Getting started with ReactJS isn't as straight forward as working with a framework like jQuery or ExtJS. There are several tools and a couple of software packages needed to create a ReactJS site with a Web API 2 backend.

First, the IDEs. Yes, there are two that I use for a single project! I use Visual Studio 2015 (you can use Visual Studio Community Edition) for creating the base Web API 2 project. Then I use Visual Studio Code to work with ReactJS. It has some built in features that make working with React easier than working with it in Visual Studio 2015 (seems odd to me too!). You can download both from https://www.visualstudio.com/downloads/.

Once you have the two IDEs set up, go ahead and create a new ASP.NET Web Application in Visual Studio. For this example, I'm calling the project 'MyProject' and saving it in 'C:\Projects\'.

Make it an empty project and include WebAPI folders and references.

Once the project is set up and being displayed in Visual Studio, open up Visual Studio Code and go to File > Open Folder and navigate to 'C:\Projects\MyProject'. This will put you in the root folder above the folder where your project files exist (you will see a 'MyProject' folder inside the selected folder).

Setting up ECMA6, ReactJS, and the Kitchen Sink

This is the part that took me a while to fully grasp, and I may still not have a complete grasp of the process! However, I can provide the steps to get you pointed in the right direction. First, you need to go out to https://nodejs.org and download NodeJS. I downloaded the current version, but you can safely download the recommended version.

This will install NodeJS and the Node Package Manager, which we will be using heavily. Next go back into Visual Studio Code and press [Ctrl + `] (that's back tick, not single quote) to bring up the terminal window. Now is where the magic starts!

We will be making a lot of calls to the Node Package Manager using the 'npm' command in the terminal window. Press [Enter] after you type each of the commands below into the terminal window.


The first two commands will set up WebPack, which will be used to transpile our non-supported code (ECMA6, JSX, etc) into supported Javascript.

npm install webpack -g
npm link webpack

Next we will initialize our project so that it can work with npm packages. This will create a package.json file and node_modules folder for our project.

npm init

Next we will install all of the dependencies we need to be able to develop our application. We need babel, and several add-ons called loaders in order to have WebPack process all of these files for use and organize them neatly at the end. You can copy this and paste it into the terminal window. This will allow us to work with ECMA6, SASS, JSON, and Images.

npm install --save-dev babel-loader babel-cli babel-preset-latest babel-preset-stage-2 babel-preset-react style-loader css-loader autoprefixer-loader sass-loader node-sass json-loader url-loader extract-text-webpack-plugin@^2.0.0-rc.3

Next, in Visual Studio Code, you will need to create a new file named '.babelrc' (it starts with a '.'). In this file, you will put the following, along with any additional presets you may need for Babel.

{
	"presets": ["latest", "stage-2", "react"]
}

Now we need to install the client-side dependencies we need for our project. This will allow our application to use the ReactJS framework and have AJAX capabilities.

npm install --save react react-dom react-router axios

Now, we need to create a file named 'webpack.config.js' and put the following code in it. This is what tells WebPack how to work with our files. We will be specifying that our processed files will go into 'C:\Projects\MyProject\MyProject\content\', and that those files will be called bundle.js and bundle.css.

var webpack = require("webpack");
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
	entry: "./src/index.js",
	output: {
		path: "MyProject/content",
		filename: "bundle.js",
		publicPath: "/content/"
	},	
	module: {
		loaders: [
			{
				test: /\.js$/,
				exclude: /(node_modules)/,
												loader: 'babel-loader',
				query: {
													presets: ["latest", "stage-2", "react"]
				}
			},
			{
				test: /\.css$/,
				loader: ExtractTextPlugin.extract({
													fallback: 'style-loader',
													use: 'css-loader!autoprefixer-loader'
				})
			},
			{
				test: /\.scss$/,
				loader: ExtractTextPlugin.extract({
													fallback: 'style-loader',
													use: 'css-loader!autoprefixer-loader!sass-loader'
				})
			},
			{ 
				test: /\.(jpg|png)$/, 
												loader: 'url-loader' 
			}
		]
	},
	plugins: [ new ExtractTextPlugin("bundle.css") ]
};

Almost There!

Whew! Now that all of that is done, we now need to set up our folder structure in our project to accommodate our files. In the project folder 'C:\Project\MyProject\MyProject\' create a 'content' folder. This is where bundle.js and bundle.css will go.

In the same folder, create an index.html file with the following.

<!DOCTYPE html>
<html>
<head>
    <title>Sampe Site</title>
    <link rel="stylesheet" type="text/css" href="content/bundle.css">	    
</head>
<body>
    <div id="react-container"></div>
    <script src="content/bundle.js"></script>
</body>
</html>

In the root folder 'C:/Projects/MyProject' create a 'src' folder. This is where all of your components and styles will go. In the 'src' folder, create a 'components' folder, an 'images' folder, and a 'styles' folder. In the 'src' folder, create an 'index.js' file. This will be the entry point into your application.
In 'index.js' type the following, changing your Routes as needed:

import React from 'react';
import ReactDOM from 'react-dom';
import Page from './components/Page';
import Missing from './components/Missing';
import { Router, Route, hashHistory } from 'react-router';

window.React = React;
				
ReactDOM.render(
	<Router history={hashHistory}>
		<Route path="/" component={Page} />
        	<Route path="Home" component={Page} />
        	<Route path="About" component={Page} />
        	<Route path="*" component={Missing} />
	</Router>,
	document.getElementById('react-container')
);

When creating components, add the *.js file to the 'components' folder, and add the *.scss file to the 'styles' folder. We will create 4 components: Page, Home, About, and Missing

Page.js

import React from 'react';
import { Link } from 'react-router';
import Home from './Home';
import About from './About';
import Missing from './Missing';
import '../styles/Page.scss';

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

        this.getNavActions = this.getNavActions.bind(this);
        this.getNavAction = this.getNavAction.bind(this);
    }

    state = {
        sectionName: 'Home',
        activeAction: 0,
        activeComponent: <Home />
    }; 

    handleNavAction(action) {
        try {
            var act = this.getNavAction(action);
            if(!act){ 
                act = { activeAction: -1, sectionName: 'Missing', activeComponent: <Missing /> };
            }
            if(this.state.sectionName === act.sectionName) { return; }
            this.setState(act);
        } catch(ex){

        }
    };

    getNavActions() {
        return [
            { activeAction: 0, sectionName: 'Home', activeComponent: <Home /> },
            { activeAction: 1, sectionName: 'About', activeComponent: <About /> },
        ];
    };   

    getNavAction(value, useAction = true) {
        var action = null;
        if(useAction){
            action = this.getNavActions().find(x => x.activeAction == value);
        }else {
            action = this.getNavActions().find(x => x.sectionName === value);
        }

        if(!action) {
            action = {activeAction: -1, sectionName: value, activeComponent: <Missing />};
        }

        return action;
    };

    componentWillMount() {
        var section = this.props.location.pathname.replace('/','');
        if(section == ''){ section = 'Home'; }
         this.setState(this.getNavAction(section, false));
    };

    render() {
        return(
            <div className="Page">
                <div>
                     <Link to="/Home" onClick={this.handleNavAction.bind(this,0)}>Home</Link> | 
                     <Link to="/About" onClick={this.handleNavAction.bind(this,1)}>About</Link> |
                     <Link to="/BadLink" onClick={this.handleNavAction.bind(this,-1)}>Bad Link</Link>
                </div>
                {this.state.activeComponent}                
            </div>
        );
    };
};

export default Page;

Page.scss

.Page {
    background-color: silver;
}

Home.js

import React from 'react';
import '../styles/Home.scss';

const Home = () => {
    return (
        <div className="Home">
		This is the Home Component
        </div>
    );
};

export default Home;

Home.scss

.Home {
    background-color: silver;
}

About.js

import React from 'react';
import '../styles/About.scss';

const About = () => {
    return (
        <div className="About">
		This is the About Component
        </div>
    );
};

export default About;

About.scss

.About {
    background-color: silver;
}

Missing.js

import React from 'react';
import '../styles/Missing.scss';

const Missing = () => {
    return (
        <div className="Missing">
		Unable to find requested url.
        </div>
    );
};

export default Missing;

Missing.scss

.Missing {
    background-color: silver;
}

Once all of this is in place, your file structure should look like the one in the image below.

Now in the Visual Studio Code terminal window, type 'webpack' and your files should be compiled and placed in the 'C:\Projects\MyProject\Myproject\content\' folder as 'bundle.js' and 'bundle.css'.

Are We There Yet?

Yes! Now all that is left is to run your application in Visual Studio (not Code) and your index.html should come up with three links and some text, all with a silver background. You can click the links to go from Home to About and then to a bad link called Bad Link to demonstrate the Missing component.

You will notice the url in the address bar for these end in #/Home, #/About, and #/BadLink. This is how React-Router's client-side MVC works. It creates a single page app that still has navigable links.

Thanks for Reading!

Thank you all for reading this tutorial. I hope it helps you to get started with WebPack and ReactJS without so much intimidation. Once you get the hang of it, you'll refer to setup instructions less and less! You can learn more about ReactJS at https://facebook.github.io/react/ and WebPack at https://webpack.github.io/.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article