JavaScript

Designing User Interfaces With React

There are a lot of JavaScript frameworks to choose from in the modern development landscape. One of the most unique and popular of these frameworks is React . React is widely known mainly because of its backing by Facebook. As a result, it has a pretty big footprint on the web. Developers know it, trust it, and love its feature set.

There are multiple tiers to what React can do, but I’d love to focus on how React can enable any developer to design modular and functional user interfaces.

What Exactly Is React?

Before we talk about creating things with React, let’s explore what exactly what React is.

Facebook’s definition of React looks something like:

“React is a JavaScript library for building user interfaces.”

While this billing could be dismissed as trendy jargon, I think it’s actually an excellent description about what the framework actually does!

React asks you to break up user interfaces into different state-driven components. We then leverage the library to help us transition between these component states. It’s a noticeably different way of thinking when it comes to building the frontend of your application.

Let’s take a login flow for example:

  1. A user visits your site and is presented with the login component.
  2. If the user enters a correct email/password, the component then submits that data for authentication.
  3. Depending on the response it receives from the authentication API, the component responds accordingly.

When we break up an application into states, there’s a need to also separate each piece of the view into components. Now, components aren’t really a brand new idea in web development. Developers have been breaking their views into reusable pieces for years. In this context, React is simply executing the process of interacting with these reusable views really well.

There’s also the matter of the JSX syntax that makes React unique. You can read a basic rundown on JSX here. JSX helps us better digest and interact with variable data in our applications.

A Technical Example in Bb

Remember that user login flow that I mentioned earlier? Let’s build it!

To set up a pretty basic environment to run React in, there’s an excellent piece of documentation that I used. I prefer to utilize Facebook’s create-react-app package in this article, but you’re free to roll your own solution as well!

Looking at App.js

Now to get down to coding. We’re going to start with a focus on App.js . This file is where we’re going to define a few classes and functions that will help us design and implement the login flow.

Initially, the file will look something like this:

App.js

import React, { Component } from 'react';
// Importing in some of our styling assets.
import logo from './logo.svg';
import './App.css';

class App extends Component {
    // When the component is rendered, this is what will appear
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>React Login Flow</h2>
        </div>
      </div>
    );
  }
}
// Export this into the global namespace
export default App;

In React, we can design components by declaring them as classes. In the example above, we’re only leveraging the render() function to create the HTML logic.

From here, we want to create another component that presents the user with a login form, assuming they’re not authenticated.

Let’s design the actual login form component first.

App.js

class LoginForm extends Component {
  render() {
    return (
      <div className="login-form">
        <input type="text" placeholder="email"></input>
        <input type="text" placeholder="password"></input>
      </div>
    )
  }
}

At initial glance, our login form class is very simple. That’s alright. We’re going to make it a bit more robust in a second. First, we’ll need to render it in our App class.

App.js

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>React Login Flow</h2>
        </div>
        <LoginForm />
      </div>
    );
  }
}

The way we render classes or components in the React, follows the syntax of: <MyComponentClass />.

I really like this syntax because it’s clean and pretty straightforward. We can pass in arguments too.

Example: <MyComponentClass argument_1=“foo” argument_2=“bar” />.

Now we’re going to add some functionality to our new component.

Adding more functionality to our views

So far, we’ve only mapped out classes that render certain sets of generated HTML. In this sense alone, React is an excellent tool for designing client-side views. However, there’s so much more to the functionality that React offers.

Let’s focus on updating the LoginForm class that we just wrote.

App.js

// Previous code 
class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    // Sets the default state of the Component.
    this.state = {
      email: '',
      password: ''
    };

    // Tells the handleInputChange method to bind / listen for events on this
    // Component.
    this.handleInputChange = this.handleInputChange.bind(this);
  }

  // Takes a change event, looks for a target's value, then updates the Component
  // state to reflect those event changes.
  handleInputChange(event) {
    const target = event.target;
    const value = target.value
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  // Triggered when we submit our form. Taking values and letting us know
  // what they are. Eventually should be extended to communicate with authentication
  // API.
  handleSubmit(event) {
    console.log("Email: " + event.target.email.value);
    console.log("Password: " + event.target.password.value);
    event.preventDefault();
  }

  // Renders HTML markdown for our Login Form.
  // Notice where we call the above methods within the HTML Markup. 
  render() {
    return (
      <div className="login-form">
        
      </div>
    );
  }
}

There’s a lot of talk about here, so we’re going to break it down into small sections. First up: the constructor.

Constructors and you

One aspect of React’s functionality that might stick out to a lot of programmers is its unique use of constructors.

constructor(props) {
    super(props);
    // Sets the default state of the Component.
    this.state = {
      email: '',
      password: ''
    };

    // Tells the handleInputChange method to bind / listen for events on this
    // Component.
    this.handleInputChange = this.handleInputChange.bind(this);
  }

If you’ve never dealt with constructors before, don’t panic! We simply leverage the constructor function to initialize our component class while also setting up the required logic to achieve the component’s purpose. Think of it like booting up your phone. We’re just setting things up for use! In our example, we’re setting up handleInputChange function.

Adding listeners on functionality

With our component class initialized, let’s explore the logic that it’s going to depend on.

// Takes a change event, looks for a target's value, then updates the Component
  // state to reflect those event changes.
  handleInputChange(event) {
    const target = event.target;
    const value = target.value
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  // Triggered when we submit our form. Taking values and letting us know
  // what they are. Eventually should be extended to communicate with authentication
  // API.
  handleSubmit(event) {
    console.log("Email: " + event.target.email.value);
    console.log("Password: " + event.target.password.value);
    event.preventDefault();
  }

The comments in the code block explain a bit about the code’s purpose. However, there are a few more things to note here: For one, there’s this idea of an event object. We’re forwarding some form of a JavaScript event (be it a click, input change, hover, etc.) and probing it for information.

In the case of our example, we’re seeing what the state of the email and password fields are at the time of submission. We need the event to track the changes of the input fields and then update the Component state to reflect that.

Trying things out

By now, we should have the resources needed to input an email/password combination and have the results printed in the console, upon submission. What we’re wanting to exercise with this demonstration is that we’re evaluating our LoginForm Component state as we interact with it.

What’s The Point of React?

So, what’s the big deal about all of this?

As we saw with our example, React can be a bit intimidating at first. There are a few new ideas presented, as well as refined old ones. While diving into the technical functionality can be a ton of fun, there are some common themes that emerge from usage.

React makes you think about design

A lot of programmers aren’t good at design. While not every programmer should be a designer (and vice versa), it’s incredibly useful to think about designing something before implementing it.

React asks you to sit down and create each piece of your application in terms of HTML and functionality. This thought process helps you break down and design a step at a time. These designed components should hopefully be reusable in the long run as well. It could be said that designing in React takes longer, but you’re gifted with concise and functional building blocks at the end.

React is really well engineered

In the development community, it’s no secret that React has been executing really well on all of its technical ideas. When I first explored the framework, I was frustrated with this lack of a application structure. However, awesome ideas like Redux have helped solve my frustrations.

React has also learned what they do best and how to somehow better execute on those strengths. So many frameworks and libraries live and die by responding to community feedback. React, in particular, has been able to thrive as time passes. As a social media user, I’m a big fan of the current state of Facebook and Instagram’s current web functionality. I believe a lot of that is due to the growth and continued success of React’s engineering.

React is not the only option

In this article, I’ve written a lot of praise for React. The framework is a really unique and acquired taste. Its also not the only option out there. I’m fairly involved with developing EmberJS applications. Ember is way different than React, and at times has been much slower than React.

However, React’s feature set has driven Ember to keep the pace with React. Other developers might say the same when comparing AngularJS to React. Either way, the prominence of React has lead to the development of better options in the JavaScript community.

Again, React isn’t for everyone, but it’s worth understanding. If the concepts and workflow that React encourages strikes a note with you, give it a shot! At the very least, you’ll walk away with a better perspective on how to create awesome user interfaces.

Reference: Designing User Interfaces With React from our WCG partner Taylor Jones at the Codeship Blog blog.

Taylor Jones

Taylor Jones is a software chef at IZEA
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button