You got a friend in me: Building a React front end “friend” for a .NET Core app

Hi there! Zac Braddy here. I am the main content creator for thereactionary.net . The Reactionary is a blog with the goal to give readers a deep understanding of the React.js javascript library. Jamie, from “A Journey In .NET Core” and I recently decided to team up and write a two part series showing how to make .NET core and React play well together.
What you will find below is an explanation of how to build the React application part for this tutorial. We do hope you’ll see this as an opportunity to maybe broaden your development horizons however if you were really hoping to read some .NET core content then worry not, you’ll find a post on how to implement the .NET core side of this application on a post Jamie wrote on thereactionary.net.
So what will we be building today? A revolutionary new service that we’ve dubbed “Bro-as-a-Service”. BaaS has been created so that you will never again be left hanging. We’ve created a virtual online bro that will never let you down. So let’s get building!
Building our React-fu dojo
I’ll assume for this tutorial that before making the brave move to continue with reading this article that you were a .NET developer who has never taken a step inside the Javascript sphere other than to piece together some jQuery to hide a button or something of the sort. Given this I think it’s safe to assume that the the first thing we’ll need to do is get node installed on your machine.
Head on over to the node.js website and grab yourself a copy of the current version of node (v7.0.0 at the time of writing this). There isn’t any wizardry here it’s pretty much just run an installer and “next” your way through.
Once you’ve finished installing node, take a moment to make sure that all has gone well the installation. To do this go ahead and bring up your favourite command console and type the following commands:
node -v npm -v
Each of these commands should return you a version number if all has gone well. You may have heard of Node and npm and there are certainly plenty of excellent blog posts out there that can give you a better explanation than me about their positives and negatives.
For the purposes of this tutorial all you need to know is that we will be using Node to compile our javascript from ES6 and JSX syntax into browser friendly ES5 javascript ready to be used in our application. It will also be used by the build pipeline that gets generated by create-react-app to host a simple local server to run our application in. What’s create-react-app? Let’s find out!
Getting the show on the road!
Now we’re all ready to start building our first React app. The first thing we need to do is install create-react-app on our machine. Create-react-app is a piece of kit that has been released by Facebook.
It’s purpose is to put together a quick and easy development environment for React.js so that you can get developing with React in the shortest time possible.
To install create-react-app we’ll use npm. You can think of npm as node’s version of Nuget. To install create-react-app head back into your console and run the following command:
npm i -g create-react-app
What is this command doing? We are telling npm to install (i) the create-react-app. The -g flag tells npm to install this package globally, this just means that it will install the package in your global repository which will make it available to you as a command that you can execute in the command line.
Let’s start using create-react-app then. Navigate your way in the command line and put yourself in a directory where you don’t mind creating a folder for the project you’ll be building in this tutorial. Once you’re there we’re going to use create-react-app to generate for us a framework to start building our react application.
We can do this by executing the following command and letting it run through:
create-react-app HiFive-ui
This will create a folder called HiFive-ui and put what is effectively a build pipeline with a hello world application inside it. Let’s have a look at it running! To do this change directory to our new projects root directory and then use the npm start command, like this:
cd HiFive-ui npm start
This will build the application and automatically open up your default browser with a copy of the app running in it. You’ll see a small page which invites you to start making changes to the code in the src folder. Let’s take up the challenge!
Let’s get Hacking
To get to our next development milestone on this app we’re going to have to pull in a few more npm packages for use in our application. To do this, first make sure that you’re in your HiFive-ui folder and then execute the following command:
npm i isomorphic-fetch es6-promise font-awesome -S
You’ll recognise the npm install command from before except this time we aren’t using the -g flag which means that the packages we ask npm to install will be installed locally in this project. The packages will live by default within a folder which will be called node_modules.
We’re installing three packages, the first is isomorphic-fetch which is a package that we can use to communicate with the .NET core back end asynchronously via ajax calls.
The second package is es6-promise which provides a polyfill for ES6 promises so that they can be compiled into something executable in ES5. Promises in javascript, if you aren’t familiar with them are kind of like a Task in C#. It allows javascript to run in an asynchronous fashion returning execution to main thread and coming back to execute callback functions when the promise resolves itself.
The third and final package is for Font Awesome which is my favourite open source font based icon set. We’re going to use to personalise our app a little bit.
Let’s begin hacking our application. We’ll start with the CSS. Go ahead and copy paste the listing below right over the top of the App.css in the src folder of the application.
.App { text-align: center; } .bro-con { animation: bro-con-spin infinite 20s linear; height: 80px; font-size: 32px; } .App-header { background-color: #222; height: 150px; padding: 20px; color: white; } .App-intro { font-size: large; margin-top: 2em; } @keyframes bro-con-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .bro-button { border: 0.012em solid #777; border-radius: 0.25em; font-size: 22px; margin-top: 2em; background-color: #d9edf7; } .bro-five-icon { margin: 0 0.2em; }
There’s nothing particularly ground breaking with regards to CSS here, certainly nothing that you won’t be cleared up after a short google so let’s just say that, essentially, the changes here are just to style the components that we’re going to add in the coming listings.
Next let’s edit the App.js file. Here’s the listing where I’ve highlighted the changes that have been made from the original App.js created by create-react-app:
import React, { Component } from 'react'; import HiFiveContainer from './HiFive.container'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <i className="fa fa-hand-rock-o fa-5x bro-con" /> <h2>Bro as a Service Bro! It's bro-tactular broseph!</h2> </div> <div className="App-intro"> <HiFiveContainer /> </div> </div> ); } } export default App;
If have rebuild the app or if you left the npm start command running in the console and it rebuilt for you’ll notice a compilation error here. The first change to notice here kind of highlights why. Line 2 has been changed to bring in a module called HiFive.container which we haven’t yet created in our application. Don’t worry, we’ll fix that in a moment.
Next, a little further down we have changed the react logo to use a font-awesome icon and also changed the header of the application to something that fits our application style a little better.
Finally in the App-intro div we are using the HiFiveContainer react component that will be defined within the files that I’ll list for you next.
Here’s where it starts getting serious
For the next file create yourself a file called HiFive.container.jsx in the src folder and copy the following code snippet into it:
require('es6-promise').polyfill(); import React, { Component } from 'react'; import fetch from 'isomorphic-fetch'; import HiFive from './HiFive.component'; class HiFiveContainer extends Component { constructor(props) { super(props); this.state = { isHiFived: false, brosponse: 'BROOOOO!', }; this.doHiFive = this.doHiFive.bind(this); } doHiFive() { this.makeServerCall(brosponse => { this.setState({ brosponse, isHiFived: true, }); this.makeServerCall(brosponse => { this.setState({ brosponse, isHiFived: false, }); }); }); } makeServerCall(cb) { var callConfiguration = {}; if (!this.state.isHiFived) callConfiguration.method = 'POST'; return ( fetch('//localhost:5000/', callConfiguration) .then(response => { if (response.status >= 400) { this.setState({ brosponse: 'No bro\'s available bro', isHiFived: false }); throw new Error('No bro\'s available bro'); } return response.text(); }) .then(cb) .catch(() => { this.setState({ brosponse: 'No bro\'s available bro', isHiFived: false }) }) ); } render() { return ( <HiFive brosponse={this.state.brosponse} isHiFived={this.state.isHiFived} doHiFive={this.doHiFive} /> ); } } export default HiFiveContainer;
It’s worth mentioning at this point that this whole application was inspired by an application that I built for a blog post on container and presentation components so if you’re interested in learning more about the finer details of the app feel free to jump over and have a read of that article. However, for the purposes of this article I’ll just be focusing on the parts that are there to talk to .NET core.
Let’s analyse the magic that is happening in the doHiFive function. You’ll see on the first line we make a call to the makeServerCall function. This function was created just to encapsulate the creation of server calls so that we only have one place to worry about error handling and so forth.
The makeServer call function takes a single parameter which is a callback function to run when the server call returns successfully. In this case we’ve defined this function using an ES6 arrow function and within this function we are setting the internal state of the Hi Five container.
The “brosponse” property is whatever response we get from the server and we’ll see how that gets populated in a moment. We also set a flag to say whether we have “Hi fived” and are waiting for our virtual buddy to cool off.
Once we’ve done all this, at the end of our arrow function, we use the makeServerCall function again. This time out intent is to hit the server on another endpoint. This other endpoint will return a result once the server is ready to accept another Hi Five.
The way that the back end for this app has been implemented is that we have a GET and POST endpoint on the root route of the application. The POST is used to perform a hi five and then a GET returns a result when the application is ready to perform another hi five.
What you can see in the first couple of lines of makeServerCall is our application deciding whether to execute a GET or a POST based on our current state of our application. I’m sure you remember from earlier that we toggle this state within the callbacks that we are passing when we invoke makeServerCall from within the doHiFive method.
You may have noticed at the top of the code listing that we are importing the isomorphic-fetch module into a variable we’ve called fetch. Well now, within the makeServerCall method, it’s time to invoke a fetch.
We give it our .NET core applications url as well as our call configuration to specify if we want to use a the GET or POST endpoint. It’s worth mentioning that if you don’t specify a method then fetch automatically performs a GET so that is how that works.
Chained on to the return value of the invocation of fetch is a call to the function “then”. This is the syntax used by a javascript promise. You see fetch returns a promise and the promise syntax goes like this
Promise.then().catch()
When the promise is resolved (i.e. a result is returned from the server) the callback that was passed into the then function is executed. You can also chain then calls if you wish and when you do this each of the then statements are executed one after the other which is what we’ve done in makeServerCall.
If you take a look at the first “then” in our chain you’ll see that all we are doing is checking for a response whose HTTP error code is greater than or equal to 400 and if we find that is the case we will set our application to graceful failure state. Then we just throw an Error to the console, this serves simply to break the execution of the promise and stop it from continuing on to the success call back.
This error handling could afford to get a lot more sophisticated if we were building a sophisticated production app but for this simple tutorial app this is enough. I guess what I’m saying here is make a judgement call and don’t be a copy paste cowboy.
Finally we return from this first “then” function the value of the line response.text(). The text function just returns the body text value of the response as a string and by returning from this value from the then we transform the value that is passed into the next then functions callback.
So this means that rather than having the entire response object being passed into the next “then” callback we pass just the body text, which we’ve already seen is what our success callback wants.
Following on in the code we can see a then which just gets passed the callback that is passed into the makeServerCall function and this is what should be called on a successful server response. Finally we have a catch block which we’re simply using to catch problems other than bad server responses like, for instance, when the server can’t be found at all! In this case we just handle the error in the same way as we did for a bad server response.
We have one last thing to do. Take a look at the render function of our container component and you’ll see that it is using a component called HiFive and this component is getting passed the value of the container components state as well as the doHiFive function which it can use to operate on the container components state.
Show me the money user interface
We’ve almost completed our little application but there’s one more component to create. Start by creating a HiFive.component.jsx file in the src folder and copy the code listing below in there:
import React, { PropTypes } from 'react'; const HiFive = (props) => ( <div> <div>{props.brosponse}</div> <button onClick={props.doHiFive} disabled={props.isHiFived} className="bro-button"> <i className={`fa bro-five-icon ${props.isHiFived ? 'fa-hand-rock-o' : 'fa-hand-paper-o'}`} /> <span>Give Hi5</span> <i className={`fa bro-five-icon ${props.isHiFived ? 'fa-hand-rock-o' : 'fa-hand-paper-o'}`} /> </button> </div> ); HiFive.propTypes = { isHiFived: PropTypes.bool.isRequired, doHiFive: PropTypes.func.isRequired, brosponse: PropTypes.string.isRequired, }; export default HiFive;
I won’t go into detail about what this component is doing here as it’s not really within the scope of the topic of “making React talk to .NET core”. Put simply this component is used to display the state from our container component created in the last section and uses it to create an interface in the form of a button to allow the user to interact with the application and modify the state of the container component.
One last thing that you’ll need to do is add a line into the index.js file in the src folder to import the font awesome CSS into the project so that the icons work. The line you need to add is highlighted below:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; import 'font-awesome/css/font-awesome.min.css'; ReactDOM.render( <App />, document.getElementById('root') );
So now we should be ready to rock and roll, if you run another npm start command you should see that the app has changed from the original create-react-app “Hello World” application and into our new app of awesomeness. If you click the button to give a Hi Five you get…………Oh. We forgot about the .NET core back end.
Starting up the back end friend
Jamie and I have taken the liberty of putting together a repository of all the source code for this tutorial so that if you aren’t interested in reading both articles but still want to follow along then you can. So now you need to either pull down the repo from here or (we hope) you can use the service you built by following along with Jamie’s article.
I strongly recommend that if you haven’t touched one or both of these technologies that you do follow along with both Jamie’s article and this one. It’s a great way to gain experience in two very cool technologies at once!
Either way, head into the project folder and run the following commands:
dotnet restore dotnet run
Your back end should now be running and if you try to hit the Hi Five button again then I expect you’ll find that you can now successfully give Hi Five’s to your new Bro-over-the-wire.
So that’s it, I hope you enjoyed this article. I know I very much enjoyed the experience of collaborating with “A Journey in .NET Core” to deliver it to you and I’d really like to think we could do more of this in the future. To make sure you don’t miss out on that don’t forget to follow both us on our social media’s which you should easily be able to find links to on each of our respective blogs. Until then though I wish you the best of luck in your respective journeys in .NET Core and React.