Introduction to React

Learn the basics of React by making a tiny app in minutes.

React is a very popular JavaScript library created by Facebook and used by many other industry leaders like Netflix, Airbnb, etc. It’s a library for building user interfaces. It introduces many new concepts about how to approach building complex user interfaces. We will explore the core concepts of how you can build apps with React. We will touch all the basics you need to know to start feeling comfortable using React.

Note: I will be using some ES6+ syntax including class, arrow functionsconst, let, import, export, etc. I suggest you to go through Introduction to ES6 if you are not familiar with the new updated syntax. We will skip all the build tools setup, thanks to Codesandbox — It gives you a ready to go Development Environment right in your browser

Getting Started

To get started, visit Codesandbox and create a new React sandbox. Once, you have created that, open index.js and Hello.js under the src directory and delete all the existing code. This is just so we have a clean sheet to start with.

Now, we will be creating an app that has an input which takes your name and says hello back to you. It’s really simple. We will be going over React basics like Components, JSX, State, Props, Event Handling in React, Stateful Components (Components as Class) and Stateless Components (Components as Functions) while creating this tiny app.

If you wanna play with the finished code, here is the link to the app hosted on Codesandbox.

First React Component

Everything in React is a component. So, let’s write our first component and it will be a “Hello World” Component. No surprises here!!

Go to index.js under src directory and write the following code —

import React from 'react';

import ReactDOM from 'react-dom';


class HelloWorld extends React.Component {

render() {

return <div>Hello World</div>;

}

}

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

That’s it, you have created your first React component. It render a <div> saying "Hello World". Let’s walk through the code we just wrote.

First, we import React from the react package. We need this to be able to create the HelloWorld component class as you can see it extends React.Component. We also need it for writing JSX.

Second, we import ReactDOM from react-dom package. We need this to mount the React app to a DOM element on the html. Look at the very last line, we use the ReactDOM.render method to mount our app (which in our case is just the HelloWorld component) on the DOM element with id of “root”. If you inspect the index.html under public directory, you will notice it has a <div> with id="root". “Mounting” means our react apps get rendered as a child node of the <div> with id="root".

Now, let’s talk about the Component. In react, we can create Component by creating a class that extends React.Component class. And every React component must have a render method. This render method and ReactDOM.render method are not related, so do not get confused between them. The render method returns what the component is supposed to render to the DOM. In our case, it is a simple <div> with some text. You will notice the return value looks like HTML and is not wrapped inside "" o ``. Hence, it’s not a string. It is what we call JSX. JSX looks like HTML and is used to simplify creating content to render.

JSX is nothing but syntactical sugar for React.createElement calls. JSX can contain any valid HTML (with certain alterations like — className instead of class attribute and “camelCased” event handler attributes like onChange instead of onchange), other React Components, JS Expressions and much more. Get to know more about JSX here. For now, this much will do.

Props and State

There are two most common ways to handle data in React — Props and State.

Simply put, props are whatever data gets passed to a component from an upper-level component, kind of like arguments to a function. While state is component specific and exclusively accessible to the component itself. A component can alter its own state data but not props data.

Let’s see how we can use Props —

Open index.js and make the following changes  

import React from 'react';

import ReactDOM from 'react-dom';

import Hello from './Hello';


class App extends React.Component {

render() {

return <Hello name="World"/>;

}

}


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

We are now importing a Hello component from Hello.js file under the same local directory. We have changed the return statement JSX to use the Hello component. We use the name attribute with the value "World". The name is a prop to the Hello component. We can access the value passed using the prop name in the Hello component. I have also changed the name of the main component from HelloWorld to App.

Open Hello.js under src directory and write the following code —

import React, { Component } from 'react';


class Hello extends Component {

render() {

return <h1>Hello {this.props.name}</h1>;

}

}


export default Hello;

Here, we are creating a new component name Hello and it returns a <h1> with some text.

Remember, when using the Hello component in the App component we passed a name prop to it. Inside the component, we can access the value passed to the name prop by accessing it as this.props.name. In this case, the value will be "World". So it will end up rendering "Hello World".

Finally, we default export the component so that we can use it from index.js

Let’s use State now —

Open index.js and make the following changes (changes are in bold) 

import React, { Component } from 'react';

import ReactDOM from 'react-dom';

import Hello from './Hello';

import Form from './Form';


class App extends Component {

state = {

name: ''

};

_updateName = event => {

const value = event.target.value;

this.setState({ name: value });

};

render() {

return (

<div>

<Hello name={this.state.name} />

<Form updateNameHandler={this._updateName} />

</div>

);

}

}


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

We are now importing another new component — Form . We are initializing state and a method named _updateName using ES6 property initializer syntax. So, in this case the state is an object with name property set to '' (a blank string value).

We pass the name value from state in App component to the Hello component as prop. We access it as this.state.name.

Now, we come to updating or modifying the state. We write the _updateName method. The method accepts one parameter event that we will receive from the onChange event handler that we will use inside the Form component. We fetch the new value from event.target.value and update the name value in the state with that.

In React, we have a special API for updating the state, i.e. this.setState. It accepts an object or a function as the first parameter and an optional callback function as the second parameter. If an object is passed as the first parameter, it uses a shallow merge of the previous state object and the object passed to form the new state object. If a function (called as an updater function) is passed, the return value of the function is shallow merged with the previous state object to form the new state. Also, the updater function receives previous state as the first parameter and props as the second parameter.

We will keep it simple and use an object to update the name value as such this.setState({ name: value }).

Note: Remember to avoid updating state directly in React i.e. like this this.state.name = value. It will not trigger a re-render and cause nasty bugs. The only place where you can assign this.state is the constructor. Always use this.setState.

Next, we use the new Form component in the render function. We pass the _updateName function as updateNameHandler prop down to the Form component.

Now, create a file under src directory named Form.js and write the following code in it —

import React from 'react';


export default props => (

<input

type="text"

name="name"

onChange={props.updateNameHandler}

/>

);

This component looks different than the App or the Hello component. This is because this is a function-as-a-component, or more commonly known as stateless component. A component which only needs a render function can be written as a function. The function’s return value is what gets rendered just like the return value of a render method in a class-as-a-component or stateful component. A stateless component cannot have any state or lifecycle hooks (more on that in an intermediate tutorial).

To handle the change event on the input element, we attach the updatNameHandler function from the props to the onChange attribute of input. React uses something called Synthetic Events for event handling, that is why it is onChange instead on onchange.

The event gets passed to the _updateName method in App, from there we get the value and update the this.state.name in App which then passes the updated this.state.name value as name props to Hello which renders the new "Hello” output.

Hence, our app is complete. It shows “Hello” at the start and when the user types in their name in the input it appends their name after “Hello”.

Conclusion

Congratulations on creating a React app. You have learned the core concepts of React and some more, through this tiny app in minutes. If you liked this article, please clap, share, comment. I will be doing an intermediate level article on React soon.

For now, go check out these to learn more -

React Official Documentation

The Beginner’s Guide to ReactJS