<< Go back

Introduction to react

React is a javascript framework for producing rich user interfaces on the web. Developed by Facebook, its widely used by many websites such as Facebook, Netflix and repl.it.

How does React work?

When writing a web app using something like jQuery you manually update the DOM (document object model – think a tree of HTML tags with everything branching off of the html tag) in response to events. A user might click 'search' and you'd fetch the search results from your server and then manually insert them into the page.

React works a bit differently to this. You tell React how your data should be displayed and how the data should be updated in response to user actions. Behind the scenes, React will work some magic to update the DOM in an efficient manner.

This magic has a name: diffing. The diff algorithm was first developed by engineers at AT&T Bell Laborities. Its purpose it to compute the difference between data. React works using diffing; updates to the DOM are slow (much slower than running Javascript code) so React works to mininimise them by creating a 'virtual' DOM. When you make a change to the data, React recomputes the virtual DOM before working out what the differences between the virual and real DOM are. It then updates only what parts of the DOM need to be updated.

How do I use React?

Configuring a React application from scratch presents a daunting task. To simplify this process, there are some easy ways to start a React app:

Once you create your React application, you should see a few different files. Open 'App.js'.

Inside App.js you should see a line of code saying class App extends React.Component {. This is an example of a component. Components are the building blocks of React applications. Each component represents a distinct part of the application. One component might be for the navigation bar and another might be for the footer. Components can (and should) be nested. For example, the navigation bar component might include a component for navigation bar links.

As part of the App class, you should see a method called render (render() {). Inside this function, you tell React how you want it to display your data. This is normally done using a language called JSX. JSX allows you to write HTML-like code in Javascript. An example of some JSX code is given below.

export default class App extends React.Component {
  render() {
    return <h1>Hello World!</h1>
  }
}

Notice how we've been able to write HTML code <h1>Hello World!</h1> in a Javascript file! Behind the scenes something called a transpiler has turned our JSX code into pure Javascript before it is output into the browser.

In its current form, however, this application isn't very useful. We'd expect a web application to be interactive and do stuff at our command. To do this, React provides something called state. All React components can have state. The React base Component class makes this easy for us. There are two important parts to state:

  1. this.state – this allows us to access the state of a given component
  2. this.setState – this allows us to modify the component's state. When we modify the state, the application will magically update itself. setState takes a dictionary as its input and modifies the state (it can also take a function as an input but that's perhaps best left for a later tutorial). setState uses that dictionary to update the state. It takes every key from the dictionary you provide and sets that key to the value you've provided in the dictionary.

For example:

-state before update
{
"username": "al-khwarzimi",
"password": "algebra"
}
-this.updateState called like
this.updateState({"username": "ada lovelace"})
-the new state now looks like
{
"username": "ada lovelace",
"password": "algebra" // note how this hasn't been modified
}

An example of this is given below:

export default class App extends React.Component {
  constructor() {
    this.state = {presses: 0}
  }
  render() {
    return <>
    <button onPress={() => {
      this.setState({presses: this.state.presses + 1})
    }}></button>
    <p>{this.state.presses}</p>
    </>
  }
}

There are a few things going on in that example which might appear weird at first; what is the onPress in the <button>? What are the curly braces inside of the <p> tag?

onPress is a prop. A prop is like a parameter, but instead of being passed to a function we pass them to a React component. The onPress prop is defined for the <button> tag and will run the function we pass it every time the button is clicked.

The curly braces tell React that you're supplying it a Javascript object (e.g. a variable, calculation, etc.) and that it should treat it accordingly (displaying the value of the variable not the variable's name).

Props are really useful if we want to nest components. Suppose I'm writing a page with a simple navigation bar and some content. I'd try to break it down into different components: one for the navigation bar and another for the content. These components can be further broken down with sub-components. The end structure might look a bit like this:

App
 - Navbar
   - NavLink
 - Content
   - ContentItem
     - ContentItemText
     - ContentFooter
       - ContentItemLink

Each component, though, will need data from its parent component. To do this, we use props. For example, the NavLink component will need to be told to where on the interweb it should point, as well as the text the link should display.

Taking the Navbar component as an example, here's one way it could be built:

const navbarLinks = [{text: "Home", href: "#home"}, {text: "Blog", href: "#blog"}, {text: "App", href: "#app"}]

class NavLink extends React.Component {
  render() {
    return <a href={this.props.href}>{this.props.text}</a>
  }
}

class Navbar extends React.Component {
  render() {
    return <div>
      {navbarLinks.map((link, linkIndex) => {
        return <Navlink href={link.href} text={link.text} key={linkIndex}/>
      })
    </div>
  }
}

There are a few new things. The navbarLinks is put in a seperate variable as an excuse to demonstrate how to render lists of data (very important in most applications). Using the map function is the most common way to do this. It takes the function passed to it and returns a new list which contains the result of applying the function to each item of the old list. So if we had the list [1, 2, 3, 4, 5] and called its map method with the function x=>x*x then the result would be [1, 4, 9, 16, 25]. This is an example of declarative programming - we're telling the computer what to do (apply the function to the list) and leaving it up to it how it wants to do that.

To pass props to the NavLink component we just pass them as tag attributes. To access a components props this.props is used.

The implementation of the rest of the site is left as an exercize to the reader. What interesting ways can you come up with to improve it?