Site icon MageComp Blog

Routing in ReactJS with Example

Routing in ReactJS with Example

Hello ReactJS Friends,

In today’s blog, we will learn about What React router is and why you should use a router in ReactJS, along with examples.

What is React JS Router?

React is a single page Application. React Router is a standard library for routing in React. In web application, Routing is a process of binding a web URL to a specific resource in the web application. In React, it binds an URL to a component. React does not support routing natively, as it is basically a user interface library. React community provides many third-party components to handle routing in the React application.

Installing React Router:

React Router can be installed via npm in your React application. Follow the steps given below to install Router in your React application:

yarn add react-router-dom

or

npm I react-router-dom

Example of React Router:

import React from 'react';
import Home from './Home'
import ‘./App.css'
import { BrowserRouter as Router, Link, Switch, Route} from 'react-outer-dom'

function App()
{
    return (
        <Router>
            <div>
                <nav>
                    <ul>
                        <li>
                            <Link to="/">Home</Link>
                        </li>
                        <li>
                            <Link to="/list">List Expenses</Link>
                        </li>
                        <li>
                            <Link to="/add">Add Expense</Link>
                        </li>
                    </ul>
                </nav>
                <Switch>
                    <Route path="/list">
                        <ExpenseEntryItemList />
                    </Route>
                    <Route path="/add">
                        <ExpenseEntryItemForm />
                    </Route>
                    <Route path="/">
                        <Home />
                    </Route>
                </Switch>
            </div>
        </Router>
);}

Const ExpenseEntryItemList = () => {
    return(
        <h1>this is ExpenseEntryItemList </h1>
    )
}

Const ExpenseEntryItemForm = () => {
    return(
        <h1>this is ExpenseEntryItemForm </h1>
    )
}

Conclusion:

Hence, this was all about Routing in ReactJS. If you have any issues, let me know through the comment section. Check other ReactJS tutorials and stay updated with us.

Happy Coding!

Exit mobile version