React in 8 easy steps: a basic introduction

 

React is a JavaScript library used in web development to build interactive user interfaces (UI) for websites. This article gives you a quick basic introduction to this valuable web developer framework.

Published on December 16, 2019

What is React?

React is a JavaScript library for building user interfaces. It lets you compose a complex UI from small and isolated pieces of code called “components”. You can think of components as custom, reusable HTML elements with content (or data) that can be changed without reloading the entire page.

In even simpler terms, React lets you display data on a webpage, let a user interact with it, change the data and make the webpage look different. It makes a webpage feel more like an app, because you no longer have to reload the entire page after every user interaction. Here’s how that works.

1. Think React

When building stuff with React, it is important to break up your user interface (design) into seperate elements. Draw boxes around every component (and subcomponent) in the design or mockup and give them all names. Next, arrange them into a hierarchy tree. Each component will be made up of internal (changeable) and external data.

In React development, developers break up every user interface design in nested components

Continue building trees of these components until you have a complete UI.

2. Meet JSX

Components are the building blocks of React. A component is a regular function that returns JSX, a syntax extensions to JavaScript. JSX looks like a template language, but it’s really just JavaScript, with all the power that comes with it. Note: Always start component names with a capital letter.

function MyComponent() {
  const name = "React"
  return (
    <div>
      <h1>Hello, {name}!</h1>
    </div>
  )
}

Inside the JSX, you may use any HTML tag to build a component. Anything between curly braces will be treated as JavaScript. In fact, You can put any valid JavaScript expression inside the curly braces in JSX, for example 2 + 2 or user.firstName or formatName(user). Mixing HTML into JavaScript (or vice versa) may be an acquired taste for experienced JavaScript developers, but this is actually what makes React awesome.

3. Reusable components

A big feature of React is reusing components. After defining a component as a function, you can keep reusing it throughout the UI. You can even use components within other components. Build up your entire UI by building trees of components.

function Greeting() {
  return (
    <div>
      <h1>Hello, React!</h1>
    </div>
  );
}

function App() {
  return (
    <div>
      <Greeting />
      <div>
        <Greeting />
      </div>
    </div>
  );
}

4. Introducing props

Components accept arbitrary inputs (called “props”) and return elements describing what should appear on the screen.

function Greeting(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
    </div>
  );
}

function App() {
  return (
    <div>
      <Greeting name="Dries" />
      <div>
        <Greeting name="Henk" />
      </div>
    </div>
  );
}

Props is the first argument to a React function component. Props may be accessed inside of curly braces to show a value. To set a prop on a child component, just pass an attribute inside it.

5. Changeable data

Instead of hard-coding data as input into functions, React lets you to use changeable internal data. This is called state.

import React, { useState } from "react";

function Greeting(props) {
  const [count, setCount] = useState(0)

  const updateCount = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You've clicked on this button {count} times.</p>
      <button> onClick={updateCount}>
        Click here
      </button>
    </div>
  );
}

You can define state with the useState function, which returns the data and a function (setCount) to change that data in an array. To start, pass in a default variable (0). You can display state by putting it between curly braces.

Note: never set state directly - always use a function!

6. Where the magic happens

Let's take another look at the code from step 5:

import React, { useState } from "react";

function Greeting(props) {
  const [count, setCount] = useState(0)

  const updateCount = () => {
    setCount(count + 1)
  }

  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You've clicked on this button {count} times.</p>
      <button> onClick={updateCount}>
        Click here
      </button>
    </div>
  );
}

In this snippet, state will update automatically when clicking the button, because we use curly braces to set the button’s attribute to a function. When you click the button, the update function updates state with a value of 1.

7. Lists and loops

In React, transforming arrays into lists of elements is nearly identical as in JavaScript. You loop over an array using map, making a list of items by returning an element from each loop iteration. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Most often you would use IDs from your data as keys.

const DATA = [
  { id: 7, trick: 'Frontside shuv' },
  { id: 8, trick: 'Three-sixty kickflip' },
  { id: 9, trick: 'Nollie shuvit' },
]

const App = () => <MyList items={DATA} />

function MyList(props) {
  return (
    <div>
      {
        props.items.map(item => {
          return <p key={item.id}>{item.trick}</p>
        })
      }
    </div>
  )
}

8. Styling elements

There are two ways to style components: one is with inline styles, the other is to give components classes and use regular CSS files. CSS classes are generally better for performance than inline styles.

import './styles.css'

const Button = () => {
  return <button className="button">A button</button>
}
.button {
  background-color: yellow;
}

Instead of class='myclass', React uses className='myclass' to assign css classes to components.

The debate about whether to separate CSS from JavaScript has become quite lively, so we’ll do an article about that later. Until then there’s plenty of excellent articles floating around for you to read.

__________

Of course, this is just a very elementary overview with some simple examples. There are plenty more concepts to expand upon, such as events, lifecycle and inheritance, but this should give you a basic idea of how React can work for you.

For further reading, check out React’s excellent official documentation or go ahead and dive straight into one of the many - often free - online courses available.

Enjoy!

react
development
javascript