React Basics | Part - 2

elwinjyot

Elwin Jyothis

Posted on February 5, 2022

React Basics | Part - 2

Sup devs! Welcome to part - 2 of the React Basics series. In the last section, I explained what React is and how React apps are written. In this post, we will start by setting up a react app and we will learn about class components in-depth.

Level - Beginners
Requirements - Good understanding of Object oriented programming in JavaScript.

Lets get started!
There are multiple ways to setup a react application. You can setup all the folders and config files, install react and your good to go. Guess what? 😎 There is an easy method, we can use the create-react-app tool to setup a react application for us.

Before that.
You need to have nodejs and npm installed in your system.

Step 1
Open a terminal or command prompt and navigate to the folder where you want to keep your project files.

Step 2
Run the below command and wait for the tool to do its magic.

npx create-react-app <app_name>
Enter fullscreen mode Exit fullscreen mode

<app_name> should be replaced by the name of your project/app. In this case we will be building an e-cart app so I will name it ecart. create-react-app will create a folder with the name of your app. Navigate to that folder and open it in your favourite text editor.

Let's analyse what create-react-app has created for us.
File structure created by create-react-app

  • node_modules

    • The first directory is the node_modules, we don't have to do anything with this folder because it contains all the packages we have installed, including React!
  • public

    • This folder contains files which won't be complied by React.
  • src

    • This is where you will do most of the work. In the src folder you can create multiple folders and files to store and manage all you components, stylesheets and other scripts. NOTE: contents of this folder will be compiled by React.
  • .gitignore

    • gitignore file is used by version control tools to skip some files and folders from tracking. Not important if you are not going to do version control.
  • package.lock.json/package.json

    • These files are utilised by npm to run or build your application. It contains all the information, packaged, commands to run your application.

Let us first move into the src folder. By default, create-react-app has written a component named App.js. We can use this file as a hub, where all the other components will come and join. Before changing anything, lets run this application.

Step 1
Navigate to the folder containing the project files.

Step 2
Run the following command

npm start
Enter fullscreen mode Exit fullscreen mode

This is an npm command issued by create-react-app in the package.json file(More about node and npm coming soon. Stay tuned! 😉). It will start a local server and open a new browser window navigated to the server. If you see the react logo spinning, then you made it!🥳. This local server will reload automatically when it detects any changes in the src files. So, everything is already sorted out.

To make your life easier, just delete all the files in src folder except for index.js, reportWebVitals.js and App.js. Create a new folder inside src folder named components. Now your directory structure should like this 👇
Directory Structure

If you check the browser now, you will get a bunch of red error messages 😶‍🌫️. Don't be intimidated, errors are our friends. We can sort that out.

Before starting with the code.

Design of the webapp

The above image is the design of the webapp that we will be making. It is a simple app in which a user can add new products, update quantity, or delete a product from the cart.

Let us first learn how to create a component.
Each react component can be created in different files. For example, in our app I need a header component which has the text ecart, we can store this component in a file named Header.jsx. Just like this all the other components of the app can be stored in different files. All these components will then be imported into the hub i.e, the App.js file, which is already imported inside the index.js file and rendered into the viewport. Let us quickly analyse the index.js file.

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
// import './index.css'; // you can safely remove this line.
import App from './App';
import reportWebVitals from './reportWebVitals';

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

reportWebVitals();
Enter fullscreen mode Exit fullscreen mode

Line 1 - import React from 'react';
This line simply imports the react library into the file.

Line 2 - import ReactDOM from 'react-dom';
The ReactDOM class is imported from react-dom library which helps in rendering components into the browser.

Line 3 - import App from ./App;
This is the line where the hub aka App.js file is imported, later in the code we can see that <App /> is called which calls the Component.

Line 4 - ReactDOM.render()
The ReactDOM class has a render method which takes in a Component and a document element as a parameter. In this case the Component is <App /> and document element is a <div> with id root. With all these parameters, react compiles the component to normal HTML string and injects it into the <div> with id root.

What! where does this root come from!!!
It resides in the index.html file in the public folder 😶‍🌫️.

public/index.html
public/index.html
All of the compiled HTML by the ReactDOM.render method will be appended to this root <div>. Now it makes sense right?😌

Lets make our first component!!😄
Inside the components folder in src, create a file named Cart.jsx. Let's write a class based component in there.

src/components/Cart.jsx

import React, { Component } from "react";

export default class Cart extends Component {
  render() {
    return (
      <div>
        <h1>Cart</h1>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

All of our HTML for Cart component will go in the render function. Always write the HTML after the return keyword, because the HTML will be returned by the render method.

Now we need to import this Cart component inside our hub. Just update the code of App.js file like below. We are also removing some imports to clear out the error messages that we got earlier.

src/App.js

import Cart from "./components/Cart";

function App() {
  return <Cart />;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the first line we are importing the Cart class that we defined earlier from Cart.jsx file (while importing components, do not write the .jsx extension after the filename).

Remember how we called the <App /> in index.js file. Just like that we are calling the Cart component(class based) inside App.js like an HTML element. Make sure you write it as a self closing tag - <Component_class_name />.

Here is a flowchart of how the components flows into the viewport. 👇
Flow chart

Revisit your browser and you should be able to see Cart text in the viewport.
Browser window

In the upcoming blogs, we will be learning about states of components and some higher order functions of JavaScript.
Stay tuned!

Thank you for reading! 😊

Part 3 -->

💖 💪 🙅 🚩
elwinjyot
Elwin Jyothis

Posted on February 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related