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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)