React Router

React Router is a standard library for routing in a React app. It enables the navigation among views of various components in a React Application and allows changing the browser URL.

Super Easy installation

Create a react app first and when you are done with that then do a simple npm install of react-router-dom as shown below.

npx create-react-app demo-app
cd demo-app

npm install react-router-dom

Now after installing react-router-dom, add its components to your React app.

import { 
    BrowserRouter as Router, 
    Link, 
    Route, 
    Switch 
} from 'react-router-dom'; 

Four main components :

  • BrowserRouter : It is the parent component and the other Child components which we need to create routes for are wrapped inside this component.
    BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL.
  • Link : It works like html anchor tags, this is used to create routes and implement the navigation in the application.
  • Route : Route is used to conditionally open a component/page based on the link selected.
  • Switch : Switch component is used to render only the first route that matches the location rather than rendering all matching routes.

Example to showcase the React Router using the above components :

import React from "react";
import {
  BrowserRouter as Router,
  Link,
  Switch,
  Route,
} from "react-router-dom";

// This site has 3 pages, all of which are rendered
// dynamically in the browser (not server rendered).

// Although the page does not ever refresh, notice how
// React Router keeps the URL up to date as you navigate
// through the site. This preserves the browser history,
// making sure things like the back button and bookmarks
// work properly.

export default function RouteExample() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About Us</Link>
          </li>
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/dashboard">
            <Dashboard />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

// You can think of these components as "pages"
 in your app.

function Home() {
  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About Us</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

Summary

In this article, we learnt about react routing using react-router-dom which can be installed as a node dependency and then used in any react app to navigate between the pages.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


JSX – Reactjs

JSX is a syntax extension to JavaScript. Stands for javascript XML. It allows us to write HTML along with javascript in react.

Look at the below variable declaration.

const test = <h1>Hello, world!</h1>;

This tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript.
JSX is recommended to use in React as it comes with the full power of JavaScript.

One Good Reason to answer Why JSX ?

Instead of artificially separating technologies by putting markup and logic in separate files, React separates concerns with loosely coupled units called “components” that contain both of them in single file.

Now adding expression in the JSX.

Example

const name = 'John Doe';
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(
  element,
  document.getElementById('root')
);

so you can add any kind of valid javascript expression inside the curly braces.

Summary

In this article, we learnt about JSX in react.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


Lifecycle methods in Reactjs

We will look into lifecycle methods in react. In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

We can add some code when a components mounts and unmounts.

shouldComponentUpdate – allows the developer to prevent unnecessary re-rendering of a component by returning false if a render is not required.

mounting – means when a component is rendered for the first time.

unmounting – means when the DOM produced by the component is removed.

render – is the most important lifecycle method and the only required one in any component. It is usually called every time the component’s state is updated, which should be reflected in the user interface.

These methods are called “lifecycle methods”.

Example

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "John"};
  }

  componentDidMount() {
	// do something
  }

  componentWillUnmount() {
	// do something
  }

  render() {
    return (
      <div>
        <h1>Hello, {this.state.name}!</h1>
      </div>
    );
  }
}

Summary

In this article, we learnt about lifecycle methods of react.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


API call in Reactjs using fetch method

In this article we will see how to do a REST API call in a reactjs component using

  • fetch method
  • inside useEffect hook

Below is a sample code which demonstrates this.

Example:

import React, { useEffect } from 'react';

function App() {

// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(
(result) => {
console.log('result : ',result);
},
).catch((e) => console.log(e))
}, [])

return null
}

export default App;

Summary

In this article, we learnt how to call a rest api end point using fetch method in react useEffect hook.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !


State and Props in React

Let’s see how React handles data. It’s done in 2 ways using state and the props.

Props

One of the method is using properties( a.k.a Props )
Lets see how to handle data using props:

export const Parent : () => {

  const name = "John";
  const address = "address";

  return(
	<Child
		name = {name}
		address = {address}
	></Child>
        )
};

interface IChild {
  name : string;
  address : string;
}

import React, FC from "react"; // FC : FunctionComponent

export const Child : FC<IChild> = (props) => {

  const fathersName = props.name;
  const address = props.address;

};

State

You can think of a state as a shopping cart, where you add/remove/modify items before the purchase.
In the same way here React has state where you can add/remove/modify data for a particular component or within the state of entire application.

import React, {useState} from "react";

export const SampleFuncComponent : () => {

const [name,setName] = useState("");
const [flag,setFlag] = useState()<boolean>;

const userName = "John Doe";
const userActive = true;

setName(userName);
setFlag(userActive);

// now you can use the state variables around this code

const completeName = name; // "John Doe"

if(flag){
const active = flag; // true
}

};

Summary

In this article, we learnt how react handles data between the components, two ways to transfer data using state and props.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !