Learn React for beginners - Quick Guide

Learn React for beginners - Quick Guide

Mastering React from Beginning

Β·

9 min read

πŸ‘‹Hey!!!

Are you a developerπŸ§‘β€πŸ’»?? If yes, then answer a question. In the last couple of years have you heard anyone saying that "Hey, I will be using HTML and CSS for my next project..."

Have you?

I at least haven't listened to something like this, I often hear people telling like I will be using React, maybe Angular or Vue. Even WordPress is becoming a thing of past for developers, new blogs are being made on top of Gatbsy, Next.js, Gridsome, 11ty...

At least for now keep the Angular and Vue on aside and let's take a look at React because exploring all the frameworks in a single article is not possible at least for me. We will talk about them some other day.

What is React?πŸ™„

React is a JavaScript library for building user interfaces, at least the official website says so. Go ahead and take a look at it... the docs also say It is Declarative, Component-Based, Write Anywhere. Ahhhh..... stop !!!

Let's take a simple approach, Have you written HTML ever? I know you have. React looks exactly the same but something different, it is like a javascript function returning an HTML. We will dive deep and know everything but for now, just keep these things in mind.

import React from 'react';

export default () => {
    return (<div> Hello World </div>)
    }

This is how Hello World in react looks like. You might be wondering we modern applications use react or any other javascript library, rather than using traditional HTML and CSS right? The problem in the old way is something like this:

Let's say you have a blog and every few minutes, some users comment on it. Now to see every comment you have to manually refresh the page and doing so will take a lot of time to reload the page, similarly, for every small change in your website, the whole webpage needs to be reloaded, which makes the website slower than it should be.

In React everything is a component, from a button to a paragraph to every single thing you write all are components.

As you see in the above image, the webpage has many areas - Like the sidebar, Ad section, Logo, Navbar, Nav Menu, etc.. All these can be separate components or a big giant component. It depends on the developer how he/she designs the page or how comfortable they are in breaking down and abstracting things in React.

Installing React:πŸ₯΄

If you don't have to react.js installed in your system then just follow the below steps:

Install Node (If you have Windows either use WSL or download node from the Official Website ):


# Add the NodeSource APT repository for Node 12
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash

# Install Node.js
sudo apt-get install -y nodejs

Install React (Linux / Mac / WSL):

sudo npm -g i create-react-app

Install React (Windows):

Run Powershell or Command Prompt as Administrator.

npm -g i create-react-app

creating a project:

npx create-react-app <APPAME>

put the folder name you want to create instead of ""

Now open the folder in your favorite code editor.

Now, after opening the folder you may see a folder structure like this:


my-app/
β”œβ”€β”€ README.md
β”œβ”€β”€ node_modules/
β”œβ”€β”€ package.json
β”œβ”€β”€ public
β”‚   β”œβ”€β”€ index.html
β”‚   └──  favicon.ico
└── src/
    β”œβ”€β”€ App.css
    β”œβ”€β”€ App.js
    β”œβ”€β”€ App.test.js
    β”œβ”€β”€ index.css
    β”œβ”€β”€ index.js
    └── logo.svg

package.json: The package.json is the heart of the entire project, it contains all the metadata of your project like what packages are used in your project, which version they are, do they need any update, etc...

node_modules: This folder is generated based on the package.json file, it is never shared between developers. And is generated when you run npm i after cloning a react project.

src: Mainly all your code lives in this folder, when you run npm start or npm build everything in this folder is rendered by React and then it puts the output in the public folder.

public: When you load your website all the files in this folder are rendered in the browser. This folder is created by compiling the src folder.

When you open the App.js file inside the src folder you will see some code like this:

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

at the very top, there are some import commands, the first import command is used to import the react library, the next two are used to import the logo and the CSS file (Yes, CSS is imported like this in react).

then there is a class, in modern React we can use a function also, which enables a new react feature called hooks. Or we may also use Const instead of class or function, Many developers do that including me.

then the render() is not being used here, mainly it is used to render some dynamic activity in react and it is most useful in conditional rendering like using if else in react.

then the next section which returns something looking like HTML right? I told you earlier it looks like HTML but is not, it is called JSX and it functions completely different.

And finally, at last, we export the class APP, The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

This is how a react code looks like.

JSX is one of the reasons why most dev hate reacts, not most of them but some do...

JSX may look like HTML but it is not HTML, You can write JSX the same way you write HTML, but there are some things you should keep in mind.

in JSX <br>, <hr>, <img> are declared like this:

<br />
<hr />
<img src="example.com/img.png" />

Look at them carefully you will understand the difference, and one more thing has you noticed in the App.js file how the Classes are defined have a look once more:

<img src={logo} className="App-logo" alt="logo" />

class is called as className in JSX because class is a reserved keyword in javascript.

Variables are added in JSX using the bracket {}, now somebody says it curly brackets, second bracket but the standard name of this bracket is bracket, google it if you don't know.

Anyway, but how the variable is assigned? Take a look at code below you will understand.

function App() {
    const name = 'Ram';

    return (
        <h1>Good Moring {name}</h1>
    );
}

URLs, SVGs, even other components can be used as variables. We can also use objects as variables when we need to pass more than one string like this:

function App() {
    const person = {
        name: 'Ram',
        age: 16
    };

    return (
        <h1>Hi {person.name},  I guess you are {person.age} year old.</h1>
    );
}

We can use CSS inside of the component, this becomes useful when we are developing a small scale app or when we need some unique styling for just one component, like if you need a special hover effect in your button, and only for that button this thing may come handy.

function App() {
    const person = {
        name: 'Ram',
        age: 16
    };

    return (
        <h1>Hi {person.name},  I guess you are {person.age} year old.</h1>
        <button style={{ color:blue, margin: '10px' }}> click it </button>
    );
}

Conditional Rendering:☠️

I will not talk much on this I will just write some code and I hope you will understand.

function App() {
    const person = {
        name: 'Ram',
        age: 16
    };

    if (loggedIn) {
        loginButton = <LogoutButton />;
    }
    else {
        loginButton = <LoginButton />;
    }

    return (
        <h1>Hi {person.name},  I guess you are {person.age} year old.</h1>
        {loginButton}
    );
}

In React there are different approaches to data flow & manipulation than in other JavaScript Libraries and Frameworks. One of them is "Props", Props is the short form of Properties. Props are usually unidirectional which means data flow from Parent Component to a Child Component.

Let's see how to use Props to React:

Let's consider this scenario we are developing a blog and it needs an author section or page. But the problem here is every time we cannot manually write a template for every author. Especially when our blog scales and have a lot of users and Guest Posts.

So, what we can do instead is to make a component for the author section or page. In this case, let's consider we need a page. And the component will look like this:

import React from "react";

const Author = ({ authName, authBio }) => {
  return (
    <div>
      <h2>Author: {authName}</h2>
      <p>Bio: {authBio}</p>
    </div>
  );
};

export default Author;

I know it is a bad author page, but anyway, Nowhere is our base component for the author page, and we have to say, 100 authors which are sourced from a database, Now I am not going to tell how to source those users from database let us keep it for another day.

And Imagine we have to generate a page from this above Author Component. And considering we have got a way to pull data from the database, I have written this template:

import React from "react";
import Author from "./Author.js";

const AuthorPage = ({ data }) => {
  return (
    <div>
      <Header />
      <Body />
      <Author
        authName={data.author.name}
        authBio={data.author.bio}
      />
      <Footer />
    </div>
  );
};

export default AuthorPage;

Here we are passing the author name and bio from the database to the child component which renders our author data and returns us our expected result, without complicating or making our codebase huge. Just think about what you would do if there was no way to pass data from one component to another.

Now we can just pass a user from the database to our template as many times we want from our backend without thinking much. Want to change the design, it will feel like breeze...

We have Learnt a lot about react today, we first learned to install Node and React in our system, then we took a look into how the default react starter looks like, then we looked into JSX and understood how it works. Then we got into Props.

But there are a few things that we didn't cover like For Loops, State and Ref in React.

State and Ref in React are complicated for a beginner, but I promise I will make a great article on what we didn't cover today in the next week. Explaining and understanding these concepts takes time and more effort and may require real examples. In a single article, If you read so much, I think you won't be able to grasp all the things. So, have a nice day, and hope you stay safe...

Thanks :)
for reading till here....😳

Did you find this article valuable?

Support Rahul Kushwaha by becoming a sponsor. Any amount is appreciated!

Β