Back button to all articlesAll articles

Discovering React - The basics

As much as I love the ever-evolving world of web development, I have not taken full advantage of it by discovering two major libraries/frameworks, namely ReactJS and VueJS.

I have stuck to Angular for many reasons, one of them being expertise and another comfort. Angular being somewhat opinionated actually made my development process more enjoyable, and seeing that ReactJS is a library that offers many ways to produce one results, I did not feel the need nor the curiosity to delve deeper into it.

But that has changed, as I truly want to have as many tools as I can on my belt, and feel the need to actually start discovering this extremely popular library. This blog post serves as documentation for my progress, but may help some people to have an approachable structure if they find themselves in a similar situation.

Installation

I always love this part, so let's head to React's installation guidelines and get started.

We're creating an application from scratch, so we'll use the convenient create-react-app package. Since we are using npm 5.2.0+, we will use npx, which will install create-react-app and execute it:

1npx create-react-app my-app 2

What does create-react-app do?
It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

Great, we now have generated a boilerplate React project, let's try it out:

1cd my-app 2npm start 3

Which opens up my browser to display:

Learning the basics

JSX

React uses the Javascript syntax extension called JSX, it produces React elements and can embed any Javascript expression when wrapped in curly braces.

The example given illustrates it rather well:

1function formatName(user) { 2 return user.firstName + " " + user.lastName; 3} 4 5const user = { 6 firstName: "Harper", 7 lastName: "Perez", 8}; 9 10// JSX element with embedded Javascript 11const element = <h1>Hello, {formatName(user)}!</h1>; 12 13ReactDOM.render(element, document.getElementById("root")); 14

After compilation, JSX becomes regular Javascript objects, therefore we can use it "inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions" like such:

1function getGreeting(user) { 2 if (user) { 3 return <h1>Hello, {formatName(user)}!</h1>; 4 } 5 return <h1>Hello, Stranger.</h1>; 6} 7

Now that's pretty cool, I can already see many use cases where JSX would have been useful in my previous projects.

Elements

The concept is very simple to understand, an element defines what we want to see on our screen, just like the one we have defined previously.

To render an element into the DOM, React uses a root DOM node, and will manage every element inside said node.

For example:

1const element = <h1>Hello, world</h1>; 2ReactDOM.render(element, document.getElementById("root")); 3

Simply renders "Hello, world" on the page.

One thing to remember is that elements are immutable, once created, we can't change its children or attributes and the only way to update the UI is to create a new element and pass it to ReactDOM.render().

Check out this Codepen example given by the tutorial.

Components

React defines components as a way to "split the UI into independent, reusable pieces, and think about each piece in isolation.".

Angular offers the component feature, so this shouldn't be too hard to understand and apply.

The easiest way to define a component is using a Javascript function:

1function Welcome(props) { 2 return <h1>Hello, {props.name}</h1>; 3} 4

But we can also use an ES6 class:

1class Welcome extends React.Component { 2 render() { 3 return <h1>Hello, {this.props.name}</h1>; 4 } 5} 6

We can render a component through elements like such:

1// props is an arbitrary input that was set in our element 2function Welcome(props) { 3 return <h1>Hello, {props.name}</h1>; 4} 5 6// Notice 'name="Sara"' which gives value to our prop 7const element = <Welcome name="Sara" />; 8ReactDOM.render(element, document.getElementById("root")); 9

This allows reusability when extracting components.

Lastly, something to keep in mind:

All React components must act like pure functions with respect to their props.

States

In React, states are similar to props but are private and fully controlled by the component, but they may only be used by components defined in a class (as opposed to a function).

Here is how we can define a state:

1class Clock extends React.Component { 2 // Declare a class constructor and pass props to it 3 // Don't forget to call the base constructor with super(props) 4 constructor(props) { 5 super(props); 6 this.state = { date: new Date() }; 7 } 8 9 // Call this.state to access state data 10 render() { 11 return ( 12 <div> 13 <h1>Hello, world!</h1> 14 <h2>It is {this.state.date.toLocaleTimeString()}.</h2> 15 </div> 16 ); 17 } 18} 19 20// No need to pass any props to our component since we are using states 21ReactDOM.render(<Clock />, document.getElementById("root")); 22

In order to update a state's value, we may use the following method from within our component (and only this method, states may not be accessed directly outside the contructor):

1this.setState({ 2 date: new Date(), 3}); 4

Lifecycle

It is essential to free up resources when components are destroyed, let's check out how we can do exactly that using React.

Mounting is when a component in rendered in the DOM for the first time.
Unmounting is when the DOM produced by our component is removed.

The respective methods (known as lifecycle hooks) in React are as follows:

1componentDidMount() { 2 3} 4 5componentWillUnmount() { 6 7} 8

They are called automatically when the conditions written previously are met.
As simple as it gets !

Events

Event handling in React is very simple.

1<button onClick={activateLasers}>Activate Lasers</button> 2

This example shows two important things:

  • React events use camelCase rather than lowercase (onClick).
  • With JSX we pass a function rather than a string to our event handler ({activateLasers}).

Normally, I should bind my methods called by event handlers, otherwise this would be undefined. But we can avoid all of that hassle by using the public class fields syntax like such:

1class Button extends React.Component { 2 // This syntax ensures `this` is bound within handleClick. 3 // Warning: this is *experimental* syntax. 4 handleClick = () => { 5 console.log("this is:", this); 6 }; 7 8 render() { 9 return <button onClick={this.handleClick}>Click me</button>; 10 } 11} 12

Otherwise, we would have to do the following in our constructor:

1constructor(props) { 2 super(props); 3 this.state = {isToggleOn: true}; 4 5 // This binding is necessary to make `this` work in the callback 6 this.handleClick = this.handleClick.bind(this); 7 } 8

Even though it is experimental, I will lean towards the first option for now as it is enabled with the Create React App package we used earlier.

In order to pass arguments to an event handler, we must do the following:

1<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> 2

Where the second argument will always be the synthetic event.

Conditional Rendering

Where Angular uses *ngIf, React seems to offer something that fits its components design.

A basic example would be:

1class Greet extends Component { 2 // Set our boolean as a state variable 3 constructor(props) { 4 super(props); 5 this.state = { isLoggedIn: false }; 6 } 7 8 render() { 9 // If true display one component, otherwise display the other 10 if (this.state.isLoggedIn) { 11 return <UserGreeting />; 12 } else { 13 return <GuestGreeting />; 14 } 15 } 16} 17 18function UserGreeting(props) { 19 return <h1>Welcome back!</h1>; 20} 21 22function GuestGreeting(props) { 23 return <h1>Please sign up.</h1>; 24} 25 26ReactDOM.render(<Greet />, document.getElementById("root")); 27

Note that there are other ways to evaluate component's rendering such as with inline If with logical && operator or inline If-Else with conditional operator.

If we wish to prevent a component from rendering, all we have to do is return null.

Lists and Keys

Where Angular uses *ngFor, React uses the map function to generate multiple elements. For example:

1const numbers = [1, 2, 3, 4, 5]; 2const listItems = numbers.map((number) => <li>{number}</li>); 3

Keys help React identify which items have changed, are added, or are removed.

We should give them to the elements inside the array to give them a stabe identity. For example:

1const numbers = [1, 2, 3, 4, 5]; 2const listItems = numbers.map((number) => ( 3 <li key={number.toString()}>{number}</li> 4)); 5

A good rule of thumb is that elements inside the map() call need keys.

Thoughts so far

React's concepts seem somewhat odd and will take time to get accustomed to, but it seems worth it as there are many advantages in their design.

We haven't seen everything that React has to offer, we still need to go through some notions such as forms and lifting state up. I will try to document them very soon.

Thanks for reading,
@christo_kade