Reactjs Walkthrough

Reactjs (or just “React” as its more commonly called) is one of the biggest competitors to Angular. I’m going to walkthrough what it is, and then follow up with a brief demo at the end.

Reactjs came out near 2011 at a time when there were a lot of different Javascript frameworks trying to do the same thing. Everyone was trying to do basic presentation of elements, but dealing with common experience and cross browser compatibility etc. Everyone was also dealing with having to literally build out the same basic scaffolding for similar content. This is where frameworks like Angular and Reactjs came in and became so powerful.

Reactjs was built by developers at Facebook as a way to easily display web elements. It has a Virtual Document Object Model (DOM) which enables performance gains (see more on that later). It also uses the “JSX” Javascript extension which makes it easy to render and insert HTML elements in your page. A nice explanation of JSX can be seen here JSX explained.

virtual dom

Whenever you have web pages they use a Document Object Model which is basically what constitutes the page in code. Every element (input field, button, etc.) has a place and is shown with markup (HTML) and decorators (CSS).

If you’re not using React, updates to your page usually require a browser to walk through the DOM to get to the element to be updated. If you have a large amount of async data calls or updates on your page, this can be taxing as the browser takes a second to walk through all those updates and render the associated elements etc.

Reactjs provides an alternative solution with the Virtual DOM. The Virtual DOM enables react to handle updates for only the element that changed. So basically if you have lots of async data calls, these calls are only going to impact the elements that change. This all translates to less required on the browser and (theoretically) faster performance of your page.

There is a whole slew of models and behaviors in Angular (and other frameworks) that provide performance gains so to an extent the advantages of the Virtual DOM can be debated. However, its a cool concept and you an see the added benefits from the basic discussion here.

how does it compare to angular

Other than the Virtual DOM, Reactjs also puts the markup and backend code together in what the documentation calls “separating concerns”.

Basically with Angular you typically have:

  1. markup (template)
  2. css file
  3. application logic file (typically .component)
  4. a spec file (for use with Karma tests)

In react you just have:

  1. a js file that has the markup and any scripting
  2. a css file for any decorations

Reactjs is also in Javascript rather than Typescript. This is both and advantage and disadvantage based on your developers. For folks that are more grounded in object oriented concepts, Typescript is the way to go. For folks that aren’t too into object oriented, plain old Javascript is easy to get running. Updates to the Javascript standard also alleviate a lot of the pain of older versions, and make it potentially advantageous to go with just Javascript for both parties.

As an Angular fan myself, I prefer typescript because it makes maintenance and architecture easy. For a nice walkthrough comparison checkout this great blog post comparing Angular, React, Javascript, and Typescript Comparing Frameworks.

so how does it work?

With a nice general understanding of what it is, lets look at “how” it is. Here is a basic Javascript project that also includes a css file (not shown).

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>

        {button}
      </div>
    );
  }
}

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

There is a lot going on here so lets break it down line by line.

First notice the import statements at the top:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

These pull in the react libraries so that you can build out a reactjs project. You can either manually install these, or use the “create-react-app” npm module that I’ll discuss later on. Also notice the “import ‘./index.css’. This css import connects an external css file to your main file so you can use any associated styling etc.

Next notice this piece at the bottom

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

This is basically the “main” method of the page that is what is called when the page initializes etc. There are more complex setups with this, but basically this is where everything starts.

If you notice in the above code, there is a class definition for the “LoginControl” which basically defines the component as a type of “React.Component”. You can think of this as similar to the app.component that you see in Angular.

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

If you see here in the constructor it sets up a “props” object which is basically just a common object that is shared by the component. Within the constructor you notice that the “handleClick” and “handleLogoutClick” methods are being registered here. This is basically setting up a listener relationship so that they can be utilized in the component. Then finally, the last step of the constructor is initializing the state object to have loggedIn as “false”.

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

If you notice here these are just the two methods that drive the component being used so this is kinda self explanatory.

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>

        {button}
      </div>
    );
  }

If you notice here the implementation of the “render” method is what is getting called by the “main” method I mentioned earlier. This is defining behavior using the “LoginButton”, “LogoutButton”, and “Greeting” objects which are defined in the next section.

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

These functions basically create an HTML button object which is injected back into the page based on the behavior. If you notice, the JSX syntax is used here as the elements are defined on the fly. If you were to do this same thing in Angular you would define the buttons in an HTML template file first. Then you could either determine their hide and show behavior or something like that in the file where the component is defined.

So this sounds all great end everything, but you probably want to see it actually working in action right? In order to do that, lets setup a local dev environment, and then you can watch it run on your computer.

running the app locally

In order to get the above code working locally, do the following

  1. Make sure you have Node.js installed on your local machine install node
  2. Next make sure to install the “create-react-app” package globally with
npm install -g create-react-app
  1. Now you can use the npm create react app package to build out a basic setup for you to copy and paste your code into. On your terminal, navigate to where you want to build out this app and then run
create-reat-app my-app
  1. Now you should have a folder “my-app” so go on into that and clear out everything thats in the “src” folder
  2. Now create an “index.js” file in the “src” file and copy and paste the following:
class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>

        {button}
      </div>
    );
  }
}

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);
  1. Now create a index.css file and copy and paste the following:
.button{
    color: blue;
    width: 20em;
}
  1. Now in the terminal go to the root directory of your project and run the following to start the app:
npm start
  1. Your app should be running and you should see a login and logout behavior as described above. For more options and to see the ins and outs of how this is running with Node.js look at the package.json file of the project.

With this sample app you should first see

Screen Shot 2018-11-14 at 3.48.00 PM

and then if you click the “login” button you should see

Screen Shot 2018-11-14 at 3.49.26 PM

You’ve just built your first React app! For a more detailed walkthrough consult the React site and the tutorials here React Tutorials.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s