Short Intro to React by Creating a Gravatar Component

Most of your work in React will be working with components. Components are the building blocks of your application.

React is a JavaScript library created by Facebook to build fast User Interfaces. React has become one of the most popular front-end libraries in the last couple of years and it is used by big players like Facebook, Instagram, Expedia, Uber, Paypal, Yahoo! and Twitter.

Since React is still gaining popularity, but some developers are afraid to try it or don’t know where to start, I decided to create a short tutorial that will bring the basics of the library. What we are going to create today is a Gravatar component that will give you enough knowledge to start creating your own components in React. I might expand the tutorial into a full application if this tutorial is well-received.

React is a Library

The main difference between React and AngularJS, Ember, and Vue is that React is not really a framework. It is just a library to work with views in JavaScript applications. You can see React as the “V” in MV* applications.

Before we Start

A prerequisite of this tutorial, you should know basic HTML, CSS, and JavaScript. This tutorial is for developers or designers that want a short introduction to the React library. You can use your favor text editor or IDE for this tutorial. But, if you want to avoid the installation process of React and just jump into coding, then you can use an online editor like JSBin or Plunker. Just make sure that you use Babel so ES6 and JSX features are availabe.

Components

Most of your work in React will be working with components. Components are the building blocks of your application and within components, you will add the functionality needed.

Let’s create HelloWorld component to see React in action. I will be using ES6 as the version of JavaScript for this example and the HTML should contain an element with the id app:

HTML
 <div id="app"></div>
Babel/ES6
class HelloWorld extends React.Component {
  render() {
    return React.createElement('div', null, React.createElement('span', null, 'Hello World'));
  }
}
ReactDOM.render(React.createElement(HelloWorld), document.getElementById('app'));

Example of the HelloWorld Component in React

If the examples don’t work at first, please click on the JavaScript/Babel frame and press the spacebar to reload the Output frame.

In the previous example, we used the class declaration to make a child class from React.Component. All components require a render method to tell React how they should look on the screen. Inside the render method, we create the HTML elements that composite our component. Using ReactDOM.render(), React inserts the component in the HTML page inside the element with the id “app”.

React.createElement creates HTML or React elements (components) inside a component via the React API. This method expects three parameters which only the first one is required:

React.createElement(type, //The type of element: HTML or a Rect component  
 [props], //The properties or attributes that this element will contain  
 [...children] // The elements that will be children of the element created.  
); 

The example has one element <div> with one child <span> that has the text ‘hello world’. If we use React.createElement() for very complex components that have nested elements, it will be a nightmare to maintain. That is why it is recommended to use JSX for this matter. JSX allows you to write XML/HTML-like code directly in your JavaScript files so you can feel comfortable while creating new elements in your components instead of nesting React.createElement functions. The following example outputs the same element but it is more readable and easier to maintain.

class HelloWorld extends React.Component {  
  render() {  
     return (<div><span> Hello World </span></div>);  
  }  
}  
ReactDOM.render( <HelloWorld/> , document.getElementById('app')); 

The last part of the code is ReactDOM.render(). This is in charge of inserting the created React components on the page inside of the element provided as the second parameter.

Example of the HelloWorld Component using JSX

Creating the Gravatar Component

Now that we have the basics of React, it is time to create our first real React component. But before jumping into the code, let’s look at the Gravatar API documentation and see what we need for the Gravatar:

  • A hash function that uses md5 to convert email addresses
  • The base URL to request the images from the server
  • The parameter used on the request to set a size for the image

The most difficult part of the Gravatar API is creating a function to create a hash using md5 because JavaScript does not have one natively. However, we can use the MD5 function on CSS-Tricks and save us long hours of coding it from scratch.

The base URL and the parameter for the size of the image are self-explanatory, and they will be more clear once we start coding the Gravatar component. You can copy and paste the function right at the top of your JavaScript file to have easy access from the component.

With what we know about React, we can create the basic structure of the component using <figure>, <figcaption> and <img> elements:

class Gravatar extends React.Component {
  render(){
    return (
      <figure>
        <img src="https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50" />
        <figcaption>John Smith</figcaption>
      </figure>
    );
  }
}
ReactDOM.render(<Gravatar/>, document.getElementById('app'));

Example of Gravatar Component with Fixed Values

This code will display an image and the text “John Smith”. But, this is not dynamic and not very practical because it does not allow you to use the component multiple times with different images and text. For that, we will use props.

Props in React

Props are the attributes added to a component so it can be further customized. They work just like any HTML attribute in standard HTML elements. Let’s modify the previous component so it can take props. The main attribute is the email so it generates the image for the gravatar. The other two attributes are size, which controls the size of the gravatar, and name that will be used to display the full name of the user.

class Gravatar extends React.Component {
  render(){
    let src = 'https://www.gravatar.com/avatar/' + MD5(this.props.email.toLowerCase()) + '?s=' + this.props.size;
    return (
      <figure>
        <img src={src} />
        <figcaption>{this.props.name}</figcaption>
      </figure>
    );
  }
}
ReactDOM.render(<Gravatar name="Bruce Lee" email="example@example.com" size="200" />, document.getElementById('app'));

Example of the Gravatar Component with Props and MD5 Function

Default Props

It is a good practice to have default values for some properties because it avoids errors while using the components and maintaining our code. For example, if you need to increase the size of the gravatar everywhere from 100px to use 200px, you just need to modify the controller and it will update every instance of the component that is using the default value instead of going one by one and modifying the size by hand. We can modify the React component to use the default size of 100 pixels and the name to an empty string. See following code:

Gravatar.defaultProps = {  
   name: '',  
   size: 100
}

Example of the Gravatar Component using Default Props

Styling the Component

The code for the component is ready. But, it does not have any style applied to it. We can simply add CSS classes to our component so they can be styled easily with CSS. As the word class is reserved word JavaScript, it’s necessary to use className instead in the JSX code.
Final Demo

Conclusion

I hope this tutorial was helpful to create your first React component. React plays well with popular backend and frontend, which allows you to use any type of technology, language or database in the backend. However, always consider your target audience and how your application should behave if JavaScript fails, is unavailable, or disabled in the browser.

Have your say