Web Development with React For Beginners

By Rasyue | On November 14, 2021

The purpose of this React Tutorial article is to guide beginners through web development with React.

React has been gaining popularity since it was first released back in 2013. Along with Angular and Vue, these 3 libraries/frameworks have been solely used for the frontend development of web application.

What is React?

React is an open-source Javascript library mainly used for building user interface or the front-end of a website.

Do I need to know Javascript to pick up React?

Since React is a Javascript library, your learning curve will be steep if you have little to none knowledge in Javascript.

However, rest assured that in this tutorial, I will guide you through all the things that you need to know to start developing your website with React.

I’m all locked in, what do I need to do now to start?

If you are ready, then let’s get cracking.

Please note that I am using Windows in tutorial.

First, make sure you have Node.js installed on your computer or machine.

After installing it, open your command prompt and run this command node -v to check if you have Node.js installed.

node -v
node -v

Depending on whatever version of Node.js you have installed, it should shows up when you run the command.

Great! Now, let’s move on to creating our first React app.

React Tutorial – Creating Your First React App

In that same command prompt that you have opened, run the following command.

npx create-react-app your-app-name
creating react app - Web Development with React For Beginners
creating react app

After the script finish running, you can now start your React app by running the following command.

cd your-app-name
npm start
react script -
react script

If you read the log in the command prompt, you will see that React is telling you to use yarn . But do not worry, we can also use npm as well.

If you are interested in yarn , feel free to read it here. Basically, yarn is just another package manager that you can use if you do not want to use npm.

Now after you have run npm start, go to your browser at open localhost:3000. Usually the script will automatically open it up for you but just in case if it does not, you can manually open it in your browser.

default react app - Web Development with React For Beginners
default react app

Congratulations! You have successfully created and run your first React app. Things will only get more interesting now.

React Tutorial – Creating Your First Page in Your React App

Before we go into details, let’s first go through the default file structure of our React app.

react file structure - Web Development with React For Beginners
react file structure

The App.js is the default React component that the application created for us. If you look into it, the file contain a functional component called App() and what it does is simply returning HTML elements.

At the bottom of the file is export default App , this is a basic Javascript way of exporting module/function/class that you want so you can import it in another file if you wish to.

Now, bear in mind that this is just the part where you defined a component. You will still need a way to actually initialized the component.

So, where do we initialized the component then?

Entry Point to the React app : index.js

Let’s take a closer look into the index.js file.

react index.js - Web Development with React For Beginners
react index.js

Now, the index.js file starts with a few libraries/modules import. We are simply importing React, ReactDOM, App and a couple more things that are not important at this point.

Yes, the App import is actually the App() functional component that we talked about earlier.

On line 7, we are using ReactDOM module and calling the render() method to render or initialize our App() functional component.

Pretty straightforward. But wait, what is document.getElementById('root')? What does this piece of code do?

When we used ReactDOM module to render our React component, we don’t actually tells it where to put it after the module has rendered it. If you remove this piece of code, it will break the application because ReactDOM module does not know where to render the component.

This piece of code document.getElementById('root') is actually telling React to grab the HTML element with the id of root and the use it to render the React component.

The next part is as you all know is where is this HTML element with id of root is residing?

In the same project folder, open public/index.html and let’s look closer in the content of the file.

react index.html - Web Development with React For Beginners
react index.html

In the index.html file if you look at line 31 you can see a HTML element div with the id root. This is the HTML element that will be used to render the React component.

Ok, that’s it! That’s all you need to know first before we go into details on React component.

React Tutorial – Functional and Class React Component

One more thing that I feel like that I need to clarify is that a React Component is the building block in any React app.

Imagine a website page where you have all these separate features. Like image carousel, carts, login, excel file reader, PDF viewer etc can be presented in a single page.

If we are to do all of those features in one single component, it is going to get messy and it will be mighty difficult for a developer to maintain or extend it.

Instead what we do is that we break them down into each separate component. This way we can have a better time to maintain or if we have to extend them later on.

So, keep in mind that in React, a single page may or may not consist of more than one component. One React component can make up a page however do not be surprised to see a few components making up a page.

With that out of the way, let’s talk about the type of React Component.

React Component – Functional and Class Component

Let’s first talk about Functional React Component first. Go ahead and create a new file called Profile.js and make sure its on the same level as App.js

profile.js
function Profile() {
    return (
      <div >
        <h1>My Profile</h1>
      </div>
    );
  }
  
  export default Profile;

/*

// you can also define a function like this using the arrow function
const Profile = () => {
    return (
      <div >
        <h1>My Profile Arrow</h1>
      </div>
    );
}
*/
  

The piece of code above is what we called as Functional React Component. The reason because we are declaring this component as a function

Open your index.js and add this up.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Profile from './Profile';
import reportWebVitals from './reportWebVitals';

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

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Go to your react page and you should be seeing this.

react profile

And with that, you have just successfully created your own functional component. Pretty nice isn’t it ? It may be a basic component at this point but we will go into details later on.

Next, let’s talk about how we can turn this functional Profile component into a Class Component.

Go back to Profile.js and replace it with this piece of code.

import React from "react";

class Profile extends React.Component {

    render(){
        return (
            <div >
                <h1>My Profile Class Component</h1>
            </div>
        )
    }
}


export default Profile;
  

Go to your react site and you should see the new class component.

profile class component

Pretty simple right? Cool!

Right now you are probably asking yourself, are there any differences between functional and class component? Where and when should I use a functional or a class component?

Comparison Between Functional and Class Component

Functional ComponentClass Component
There is no render() method in functional therefore you don’t always have to return HTMLAlways need a render() method to return HTML
For when you want to quickly build a simple component without having to deal with complex logic or statesFor when you need to create complex component dealing with states and logic
Often used as a component whereby props got passed to it and used to render a part of UIOften used to fetch data and manipulate it before passing it down as props to child component
Have access to hooksHave access to lifecycle methods
Comparison Table

To help you understand this better, let’s go into more details on Class Component.

React Tutorial – React Class Component

First, let’s create a new file and called it About.js

Inside the file, paste the followings.

import React from "react";

class About extends React.Component {


    render(){
        return (
            <div >
                <h1>About Class Component</h1>
            </div>
        )
    }
}


export default About;

Pretty simple piece of code. Now let’s make it more interesting.

In React, you will almost always see or hear the terms Lifecycle methods, States and Props. What are these things? Allow me to explain.

React Lifecycle Methods

Lifecycle methods are unique built-in React methods that allow us to determine the behaviour of a component.

Why is it called lifecycle? Because every React component goes through a lifecycle or in simpler term, a series of events. These series of events or lifecycle starts with the initialization of the component, the update of the component, the rendering of the component and finally the deactivation or deinitialization of the component.

The correct terms are as per below.

  1. Mount – Initialization of a component.
  2. Update – Update of a component.
  3. Render – Render of a component.
  4. Unmount – Deinitialization of a component.

Using the Lifecycle Methods we can do a lot of things during the above series of events. Below are the lifecycle methods that we can use.

  1. constructor() – this method is run immediately during the Mount event of a component
  2. componentDidMount() – you can use this method to run any logic right after your component has been Mounted but before the Render event.
  3. render() – yes, you probably have seen this earlier but this is also a lifecycle method that you used to Render a component.
  4. componentDidUpdate() – a method that is called after an update happens in a component.
  5. componentWillUnmount() – a method that is called right before the Unmount event of a component. This method is usually used for clean-up like destroying your subscribe method.

There are others Lifecycle methods that I did not list in the above but the 5 methods above are the basic and mostly used that you need to know.

React States

Now that you know about Lifecycle Methods, let’s talk about States in React Component.

In simpler term, a React State is actually just a JavaScript object that is used as a representation of information of the component situation. During the lifecycle of a component, a state may or may not change.

When a component State changes, an update occurs and the component re-renders.

this.state = {
  name: "rasyue",
  blog: "rasyue.com"
}

The above is a simple example of a State in a React Component. During the lifecycle of a component, the information above may changed. But how do we change it?

We can change a State simple through using the setState method which is also a built-in React method. See below example.

this.setState({
   name: "rasy",
   blog: "rasy.com"
})

Always remember that setState is asynchronous therefore when do not expect for it to happen instantly. This means when you called setState in one line, you must never assumed that it will occur immediately in the next line of code.

React Tutorial – React Class Component with Lifecycle Method and State

Now, let’s make our About component more interesting.

In your About.js , replace with the followings.

import React from "react";

class About extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            name: "Rasyue",
            website: "rasyue.com",
            post: "React for Beginners"
        }
    }

    render(){
        return (
            <div >
                <h1>About Class Component</h1>
                <p>{this.state.name}</p>
                <p>{this.state.website}</p>
                <p>{this.state.post}</p>
            </div>
        )
    }
}


export default About;

Next, go to index.js and add your About component into the stack.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Profile from './Profile';
import About from './About';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
    <Profile />
    <About />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

You should be seeing this right now after you refresh your React page.

Pretty neat huh? Simply adding constructor() method allows you to hold information in your About component state.

To help you understand this better, let’s go through one by one starting with the constructor().

consructor(props){
  super(props)
  this.state = {
   name: "Rasyue",
   website: "rasyue.com",
   post: "React for Beginners"
 }
}

First the super(props) is a line of code that we need as a reference to the parents constructor(). In this case since we are extending React.Component, we are referencing to its constructor().

If this confused you, just make sure you don’t forget to add super(props) in your Component constructor(). You don’t really have to go into details regarding this.

Next, the this.state, like every other variable, we are just declaring a variable and then set some information in it. Nothing too complex.

Now, let’s try to change our Component with a different information through using this.setState().

Replace your About with the followings.

import React from "react";

class About extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            name: "Rasyue",
            website: "rasyue.com",
            post: "React for Beginners"
        }

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        this.setState({
            [event.target.name]: event.target.value           
        });
    }

    render(){
        return (
            <div >
                <h1>About Class Component</h1>
                <input type = 'text' name = 'name' value = {this.state.name}   onChange={this.handleChange}/>
                <input type = 'text' name = 'website'  value = {this.state.website} onChange={this.handleChange} />
                <input type = 'text' name = 'post' value = {this.state.post}  onChange={this.handleChange}  />
                <p>{this.state.name}</p>
                <p>{this.state.website}</p>
                <p>{this.state.post}</p>
            </div>
        )
    }
}


export default About;

Reload your browser and test it out.

Before we go into building our website, let’s quickly talk about Functional Component.

React Tutorial – React Functional Component

A Functional React Component is basically a function that will render a JSX element.

For example:

// functional React component

function Contact() {
    return (
      <h1>Contact Component</h1>
    );
}
  

// also a functional component but using arrow function
export const ContactUs = () => {
    return (
      <h1>Contact Us Component</h1>
    );
}
  

export default Contact;

The above shows two different way that you can create a functional React component. Both works and its really up to you to choose.

However, I would recommend that you use the first method if your React component is big and complex. Use the second method for simple component.

Import them in App.js and display it.

With these out of the way. Let’s move on to the next step.

React Tutorial – Making HTTP/API Call

Now that we have learnt about React component, state and lifecycles.

The next step will be to learn how to make a http call in React.

Like any other front-end frameworks, making a http call is essentials for the application to be able to talk to the backend application to get data/information.

Doing that will allow you to display dynamic data, protected information and so on to the user.

Let’s get to work.

Before we can make our http call, we will need to install axios

You can opt to use fetch and I will be showing how to use axios in this tutorial.

npm i axios

Next, create a new component. We will start with Class Component and move to Functional Component.

import React from "react";
const axios = require('axios');

class Entry extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            data: [],
            count: 0         
        }   

    }


    getData = () =>{

        axios.get('https://api.publicapis.org/entries')
        .then((response) => {
            console.log(response.data.entries)
            this.setState({
                count: response.data.count,
                data: [...this.state.data, response.data.entries]
            })
            
        })
        .catch((error) => {
            // handle error
            console.log(error);
        })

    }

    render() {

        return (
            <div>
                <h1>Hello Entry</h1>
                <button onClick={this.getData}>Get Entry Data</button>
                <p>Entry Count: {this.state.count}</p>

                {this.state.data.length > 0 
                    ?(
                        <>  
                            <div>
                                {this.state.data.map((data, index) => {
                                   
                                    // here's a little exercise for you, find out why the data is not displaying
                                    <p key = {index}>{data.Description}</p>
                                    
                                })}
                            </div>
                        </>
                    )
                    :(
                        <>

                            <p>No data</p>
                        </>
                    )
                }
            </div>

        )
    }
}


export default Entry

Import this component in App.js and refresh.

import logo from './logo.svg';
import './App.css';
import Entry from './Entry'


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>      
        <Entry />
      </header>
    </div>
  );
}

export default App;

You should have something like this.

Next, let’s see how we can do the same with functional component.

import React, {useState} from "react";
const axios = require('axios');

function Entry(){

    const [data, setData] = useState([])

    const getData = () =>{

        axios.get('https://api.publicapis.org/entries')
        .then((response) => {
            console.log(response.data.entries)           
            setData(response.data.entries)
        })
        .catch((error) => {
            
            console.log(error);
        })

    }

    return (
        <div>
            <h1>Hello Entry Functional</h1>
            <button onClick={getData}>Get Entry Data</button>
            <p>Entry Count: {data.length}</p>

            { 
            
                // more exercise for you, try to display the data using .map()

                /*

                data.map(item => {


                })
                */
            }
        </div>

    )
    
}

The above shows how we can do the same exact thing but functional style.

Copy and paste the above code and refresh.

You will see that you will have exactly the same functionality.

The End But not Really…

Anyway, this is it for the first part of this tutorial.

In the second part, we will learn how to build our website with the correct web architecture and development approach.

Stay tuned! The second part : Web Development with React For Beginners – Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*