← Back to main site

Learning React Basics

March 30, 2019

React is a JavaScript library for creating modern single-page web UI.

Getting Started

Let’s see a very simple way to add React to a HTML page. To get started, let’s have a page with nothing but a <div> element.

<html>
    <head>
        <!-- We'll import libraries here -->
    <head>
    <body>
        <div id="app"></div>
        <script type="text/babel">
            /* We'll add React JS code here */
        </script>
    </body>
</html>

To use React, we’ll add three scripts from CDN —

  • React - For making components
  • ReactDOM - For manipulating DOM using React components
  • Babel - For the browser to make sense of JSX syntax

So our head tag will become —

<head>
    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<head>

React building blocks are called Components. They are small, reusable pieces of markup written in a syntax called JSX (JavaScript XML), which resembles HTML. Think of JSX as just HTML with a few extra abilities.

Adding a Component

There are two ways to create a component.

  1. Create a function which returns JSX.
  2. Create a class extending from React.Component having a render method.

Let’s create a class called Greeting in the script tag under the body

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

And voila! We’ve created our first component.

Now in order to render this in the DOM, we need to call ReactDOM and give it this component that we’ve created and give it the HTML element where this should be rendered.

ReactDOM.render(
    <Greeting />,
    document.getElementById("app")
);

So our full page will look like this—

<html>
    <head>
        <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
		<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
    <head>
    <body>
        <div id="root"></div>
        <script type="text/babel">
            const Greeting = () => (
				<h1>Hello World!</h1>
			)

			ReactDOM.render(
				<Greeting />,
				document.getElementById("app")
			);
        </script>
    </body>
</html>

The result after running this page in browser is as you expected— Hello World

Congratulations! You’ve just created your first React application.

How this works?

React uses something called as a virtual DOM of the UI components. It is a tree of component objects stored in memory. It resembles the actual DOM that is rendered on page. The render() method creates it.

Every time the object changes, React compares the changes between the new state and the old state and using the differences, a new virtual DOM is created. After that React updates only the changed elements in real DOM accordingly. This is done using ReactDOM.render().

How data is handled?

The two types of data in React are —

  1. Props — external, comes as input, can’t be changed by component itself
  2. State — internal, private to component

Props

Let’s add a property named to in order to change whom the Greeting should be addressed.

ReactDOM.render(
    <Greeting to="Joey" />,
    document.getElementById("app")
);

We can access this property from the Greeting class. We can show a JavaScript expression in JSX by enclosing in curly braces.

class Greeting extends React.Component  {
    render() {
        return (<h1>Hello {this.props.to}!</h1>)
    }
}

After saving and refreshing the browser, we can see Hello Joey in the browser.

State

The data that should be internal to the component and can be changed by the compoent is stored in a class variable called state.

class Greeting extends React.Component  {
    constructor() {
        super()
        this.state = {
            to: "Monica"
        }
    }
    render() {
        return (<h1>Hello {this.state.to}!</h1>)
    }
}

ReactDOM.render(
    <Greeting />,
    document.getElementById("root")
);

How to change the state?

We should never modify the state directly. We need React to compare and make changes to virtual DOM, remember?

Hence, we use a function provided by the React.Component called setState() to change it.

class Greeting extends React.Component  {
    constructor() {
        super()
        this.state = {
            to: "Monica"
        }

        this.changeUser = this.changeUser.bind(this)
    }

    changeUser() {
        this.setState({
            to: "Chandler"
        })
    }

    render() {
        return (
        <React.Fragment>
            <h1>Hello {this.state.to}!</h1>
            <button onClick={this.changeUser}>Change User</button>
        </React.Fragment>
        )
    }
}

Adding styles

Given that class is a reserved JavaScript keyword, it can’t be used in JSX for adding CSS classes. Instead, we use className property.

<button className="btn btn-primary">Change User</button>

We can also use the style property to set CSS. It expects a javascript object.

<button style={{
        color: 'green'
    }} >Change User</button>

After refreshing, you can see the changes— Color Style

By now, you have got a basic understanding of what React is and how it works. We’ll see how to create a full React application using modern JavaScript in the next post.


{author}

Written by
Vibhav Churi