roxxhub

ReactJS: A simple introduction

What is React ? Why should we use it ?

React, also called react.js is a javascript library used to create frontend UI (user interface) of a web application. It does it by letting the users create different reusable components. React makes it easier to do frontend development than it is while using vanilla javascript. It was created and managed by facebook.

In this blog we’ll see it’s basics and create a simple web app using it. The final code will be updated here – https://github.com/RoxxHub/reactJS/tree/main

The features of React

  1. It uses JSX (javascript xml), a language created by facebook itself which lets users write html inside javascript withoud createElement() or appendChild() methods. JSX is converted into browser readable format (vanilla js) using transpilers like Bable.
  2. It creates virtual DOM.

Creating a Project folder

First we’ll simply create a folder inside where we’ll be doing everything. You can do that by typing.

mkdir my-site
cd my-site

As you can see, I have named the project ‘my-site’

Creating a react app

npx create-react-app my-app

By writing the above code in the terminal, we are using the ‘create-react-app’ library which creates all the necessary files, including the ‘node modules’ folder inside the folder ‘my-app’ (it could be anything).

npx is a package runner which is used to use any package without installing it.

After the setup is complete, you will get all these files inside your ‘my-app’ folder.

react app
npm start

Running the above command will start your server which can be accessed in localhost:3000 in your browser.

react app

This happened because of files inside the src folder.

For this tutorial I would ask you to delete everything inside the src folder as we’ll be seeing how everything works from scratch.

Creating an index.js file

First we’ll create a file called index.js and write the following code there.

import React from 'react';
import ReactDOM from 'react-dom/client';

ReactDOM.render(
    <h1>hi bruh</h1>
, document.getElementById('root'));

NOTE: this code will not work for you if you are using react version 18+. But this will

import React from 'react';
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <h1>hi bruh</h1>

);

In react, it is necessary to create an ‘index.js’ file as React looks for it and somehow links it with the “index.html” file in the public folder.

As you can see, ReactDOM.render takes 2 arguments- the jsx code and the sections where you want to render it, which in our case is <div> with id ‘root’ .

And in newer versions, you first create a root object and then render the code.

react index.html

Save the changes and react will automatically restart the server. You must get something like this.

You can make changes inside the render method and they would appear in the browser.

JSX in depth

As you probably know, react uses something called JSX inside the render method. But is JSX too hard to learn. Well the answer is no. There are only a few differences between JSX and vanialla JS and it is recommended to take a look at it before reading any further. All the differences are clearly explained here – https://www.w3schools.com/react/react_jsx.asp.

Components

We often don’t put every line of code in a single file, instead we make different files and import them wherever they are used.

React Lets us import custom functions / classes from different files which consist of the render method. In most of the cases, we’ll be using the functions components. In fact there is no case we are going to need the class components as they are considered out dated.

Lets say we create two files, navbar.js and home.js.

Home.js
export const Home = () => {
  return (<>
  <div className='main'> 
  <h1>this is the homepage</h1>
  
  </div>
  </>
  )
}
Navbar.js

export const Navbar = () => {
  return (<>
    <div class="sidenav">
  <a href="/home">Home</a>
  <a href="/about">About Us</a>
  <a href="/contact-us">Contact</a>
</div>

</>
  )
}

Now we will import these as components in the index.js file like this.

import ReactDOM from 'react-dom/client';
import { Home } from './home';
import { Navbar } from './navbar';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<>
<Navbar/>
  <Home/>

</>

);
react app

You should create your own about-us and contact component too and import them. Just like we created for Home.js. Just don’t forget to give them className=’main’ (Why?)

Adding CSS

Of course we are still missing the most important thing in this, which is adding CSS. there are plenty of ways to add css in our app . But for now we will simply create an index.css file and import it in our index.js file.

You could have created different css files for each of our component, but for this tutorial, we are just keeping everything at one place.

index.css
body {
    font-family: "Lato", sans-serif;
  }
  
  .sidenav {
    height: 100%;
    width: 160px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    padding-top: 20px;
  }
  
  .sidenav a {
    padding: 6px 8px 6px 16px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
  }
  
  .sidenav a:hover {
    color: #f1f1f1;
  }
  
  .main {
    margin-left: 160px; /* Same as the width of the sidenav */
    font-size: 28px; /* Increased text to enable scrolling */
    padding: 0px 10px;
  }
  
  @media screen and (max-height: 450px) {
    .sidenav {padding-top: 15px;}
    .sidenav a {font-size: 18px;}
  }
update in index.js
import "./index.css"

react-router-dom

react router dom is an npm package used for creating single page applications. In the app we have just made, you might notice when we go to a different page, the entire site reloads. Using this package, we only render the part of the website, i.e. component which is changing. For example while going to /about from / we just need to render the /about component(if any), not the navbar.

To use it, first we’ll install it

npm i react-router-dom

Then we import it (index.js)

import {
    BrowserRouter as Router,
    Routes,
    Route,
} from "react-router-dom";

and update the render like this

<Router>
        <Navbar />
        <Routes>
            <Route path='/' element={<Home />} />
            <Route path='/about' element={<About />} />
            <Route path='/contact' element={<Contact />} />
        </Routes>
    </Router>

We wrap everything inside the <Router>. Then we wrap all the components inside <Routes> which need to change in our single page app( thats why we exclude navbar).

We someone goes to ‘/’, only home is rendered. and so on.

also we need to use “Link” tag from this package to function everything properly. So we update the navbar like this

import { Link } from "react-router-dom"
export const Navbar = () => {
  return (<>
    <div class="sidenav">
    <Link to="/">Home</Link>
  <Link to="/about">About</Link>
  <Link to="/contact">Contact</Link>
</div>
</>
  )
}

Now you will notice, when we change our page in our app, the entire app doesn’t reload, but only the part that needs to be. This actually increases our site’s speed.

Conclusion

This was just a simple introduction to react. Of course there are several other things too. One other very important concept is that of hooks. Which is nicely explained here.

I hope this tutorial was helpful.

1 thought on “ReactJS: A simple introduction”

Comments are closed.