January 26, 2017

/

React Quick Start Tutorial

React Quick Start Tutorial

Unfortunately I feel a lot people looking to get into React get bogged down with all the buzz around Flux or Redux, server rendering, build tools etc… All of which are not actually part of React itself. I thought I’d write a short tutorial to teach you the basics.

This is part 1 of 2 and will deal with the core concepts of React, creating a component and how “props” work. The second article will focus on component state and the life-cycle of a React component.

The Component

At its core React is a component oriented U.I. library built in JavaScript. It has been proven in a large number of different use cases and I think is worth learning.

A component is a discrete part of a U.I. and React comes with all of the familiar HTML elements (such as <div> and <p>) which you can use to build your own custom components and interfaces all in JavaScript with no HTML… In your files. At the end of the day React transforms your JSX (more on this soon) into the HTML the browser will understand.

The key to React is that is components all the way down. You create a root component which is your “app” and your “app” is made up of more components.

ES2015 and JSX

React was one one of the first frameworks to embrace ECMAScript® 2015(also known as ES2015 or ES6) which is the latest ratified standard for JavaScript as 2015. When Facebook first release React this was not the case yet but a lot of people were using ES2015 it and transpiling their code with something like Babel.

JSX is essentially syntactic sugar that allows you to use a very HTML-like XML syntax in your JavaScript. Instead of having separate HTML template. Although you can use React without JSX, and I don’t want to go into the argument about it, I would say this:

If you want to use React then you should use JSX, if you don’t like it their are many other great options out there. But you don’t have to use use.

Basic Component

Since this is a quick start lets get into an example. In this tutorial I’m going to build a very simple beer shop app in react. Say we want to show a simple welcome message on our app:

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div className='App'>
        Welcome to React!
      </div>
    );
  }
}

export default App;

NOTE: I’m going to assume you already know the ES2015 syntax I’m using here with classes and import/export statements. If you don’t go have a quick google, but once again like JSX you don’t need to use this syntax but its a lot easier if you do (and the React team recommend you do).

This is a basic example of a react component. I have imported the Component class from the ‘react’ package and this class has one method: render(). This is all you need to do to create a component. So if a component has no logic and simply displays data or plain HTML all you need is a render method.

Notice though how I have className='App' rather class="App". The reason it is ‘className’ and not ‘class’ is because the React authors decided to go with the JavaScript Web Api that uses camelCase rather than hyphen-case that html uses. The second thing you’ll notice is I used single quotes rather than double. This is stylistic and I just prefer to use single quotes in JavaScript.

Component “props”

Props are just a hipster way of saying properties and they are essentially the same thing as html attributes. In the previous example we were using the className prop which exists because under the the elements in your JSX are just an abstraction based on the html elements they represent. So if an HTML element has special attributes then so does the corresponding element in React. In reality you can just treat it like HTML except the minor differences such ass className.

If that just sounded like garbage here is an example:

class App extends Component {
  render() {
    const { appName } = this.props
    return (
      <div className='App'>
        Welcome to {appName}!
      </div>
    );
  }
}

I’m passing the appName through as “props” and I can access these props at the key this.props:

const { appName } = this.props

Note: Here I am using the Deconstructing Assignment syntax which you should read more about in this great MDN article

I haven’t actually shown you how to pass the props to the component. First I need to show you how to render a component in an html page…

Rendering a component

React is made up of two parts:

  1. The core part is what we have dealt with so far, the HTML abstractions, and the component model (with its life-cycle hooks that I won’t go into in this intro article).
  2. The other part is the rendering part and in the case of the browser environment we use the package “react-dom”. This package does the translation of your application’s component JSX markup, state and props into the HTML that gets you see in your browser. That is all react is!

To render a component you have to import ReactDOM, create a class that inherits from React.Component, select an element to render into (using plain old JavaScript e.g. getElementById()) and pass them to the ReactDOM.render(reactElement, domContainerNode) function.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

I have imported both the react package (this must be imported if using JSX), the ReactDOM library and my App component from earlier that is in another file called App.js. Then I pass the <App /> component as the reactElement to render and select an element with the id="root" from the HTML page.

Passing props to a component

As promised below is how you pass the “appName” prop to the App component:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App appName='React' />,
  document.getElementById('root')
);

props.Children

One special prop is the ‘children’ prop. This is an array of the children components that were passed to the component. This could have any where from 0 to x elements in it or it could just be a string (such as in a <p> tag).

As explained in the great guide about composition over inheritance
this allows you to have components that don’t need to know about the children ahead of time but are still able affect how they are rendered or what data is passed to them.

One file example React apps

Instead of going into lots of details about props with words here are some simple one file examples of a react app:

The example above

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
  render() {
    const { appName } = this.props
    return (
      <div className='App'>
        Welcome to {appName}!
      </div>
    );
  }
}

ReactDOM.render(
  <App appName='React' />,
  document.getElementById('root')
)

A New Zealand craft beer listing app

You’ll notice in this one I have created a custom component called CarftBeer and showed three ways of creating react components:

  • A class that inherits from React.Component
  • A regular function that takes props as parameter and returns JSX
  • An arrow function that takes props as a paramter

Note: You’d have to choose one and remove the other two to make this example compile

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

// Written as a class
class CraftBeer extends Component {
  render(){
    const {beerName, brewery} = this.props
    return  (
      <div className='craftBeer'>
        <h3>{beerName}</h3>
        <p>Brewrey: {brewery}</p>
      </div>
    )
  }
}

// Written as regular function
function CraftBeer (props) {
 const {beerName, brewery} = props
  return  (
    <div className='craftBeer'>
      <h3>{beerName}</h3>
      <p>Brewrey: {brewery}</p>
    </div>
  )
}

// Written as arrow function
const CraftBeer = ({beerName, brewery}) => (
  <div className='craftBeer'>
    <h3>{beerName}</h3>
    <p>Brewrey: {brewery}</p>
  </div>
)

class App extends Component {
  render() {
    return (
      <div className='App'>
        Welcome to Crafty Code!
        <CraftBeer beerName='Book Binder' brewery='Emersons' />
        <CraftBeer beerName='Pernicious Weed' brewery='Garage Project' />
        <CraftBeer beerName='Bitter Bitch' brewery='Parrot Dog' />
      </div>
    )
  }
}

ReactDOM.render(
  <App appName='React' />,
  document.getElementById('root')
)

Example of a wrapper component

Here I have a simple sidebar component that allows me to change the look of my widgets but I don’t need to know anything about what they really are or what they contain:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

const Sidebar = (props) => (
   <aside className='sidebar'>
     {props.children}
   </aside>
)

class App extends Component {
  render = () => (
    <div className='App'>
      <div>Main Content</div>
      <Sidebar>
        <div className='widget'>
          Widget 1
        </div>
        <div className='widget'>
          Widget 2
        </div>
      </Sidebar>
    </div>
  )
}

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

That’s it! Obviously we have only created one component here but you can nest components infinitely to create a tree that represents your application. In my next article I am going to introduce the React component life-cycle and build a (semi)real world-example for a working React app.

Seth Reid

/

React Quick Start Tutorial