Assignments Of Day 14: Introduction to React Router

Rashmi Mishra
0

AssignmentsOf Day 14: Introduction to React Router

Assignment 1: Basic Routing Setup

Task:

Create a simple React application with three pages:

1.  Home

2.  About

3.  Contact

The pages should be linked using React Router. The Home page should be the default landing page, and the other pages should be accessible through the navigation menu.

Solution:

1.  Install React Router:

bash

Copy code

npm install react-router-dom

2.  Create the Pages:

  • Home.js

javascript

Copy code

import React from 'react';

 

function Home() {

  return <h2>Welcome to the Home Page</h2>;

}

 

export default Home;

  • About.js

javascript

Copy code

import React from 'react';

 

function About() {

  return <h2>About Us</h2>;

}

 

export default About;

  • Contact.js

javascript

Copy code

import React from 'react';

 

function Contact() {

  return <h2>Contact Us</h2>;

}

 

export default Contact;

3.  Setup Routing in App.js:

javascript

Copy code

import React from 'react';

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

import Home from './Home';

import About from './About';

import Contact from './Contact';

 

function App() {

  return (

    <Router>

      <div>

        <nav>

          <ul>

            <li><Link to="/">Home</Link></li>

            <li><Link to="/about">About</Link></li>

            <li><Link to="/contact">Contact</Link></li>

          </ul>

        </nav>

 

        <Route path="/" exact component={Home} />

        <Route path="/about" component={About} />

        <Route path="/contact" component={Contact} />

      </div>

    </Router>

  );

}

 

export default App;

Explanation:

  • The Home, About, and Contact components are created.
  • We use BrowserRouter to wrap the app for routing.
  • The Link component is used for navigation, and Route is used to define the different pages.
  • exact ensures that the home page is only shown at the exact / path.

Assignment 2: Dynamic Routes with Parameters

Task:

Create a dynamic route that accepts a username as a parameter and displays a personalized message on the Profile page. The route should look like /profile/:username.

Example:

  • URL /profile/john should display "Welcome to the profile of john".
  • URL /profile/jane should display "Welcome to the profile of jane".

Solution:

1.  Create the Profile Component:

javascript

Copy code

import React from 'react';

import { useParams } from 'react-router-dom';

 

function Profile() {

  const { username } = useParams();

 

  return <h2>Welcome to the profile of {username}</h2>;

}

 

export default Profile;

2.  Modify App.js to include the dynamic route:

javascript

Copy code

import React from 'react';

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

import Profile from './Profile';

 

function App() {

  return (

    <Router>

      <div>

        <nav>

          <ul>

            <li><Link to="/profile/john">John's Profile</Link></li>

            <li><Link to="/profile/jane">Jane's Profile</Link></li>

          </ul>

        </nav>

 

        <Route path="/profile/:username" component={Profile} />

      </div>

    </Router>

  );

}

 

export default App;

Explanation:

  • The Profile component uses the useParams hook to get the username parameter from the URL.
  • The Route component uses the dynamic path /profile/:username to render the profile based on the URL.
  • The Link component creates clickable links to different profiles.

Assignment 3: Nested Routes

Task:

Create a Dashboard component with two sub-routes:

1.  Overview

2.  Settings

The main Dashboard component should render a navigation menu for these sub-routes.

Solution:

1.  Create the Dashboard Component with Nested Routes:

javascript

Copy code

import React from 'react';

import { Route, Link } from 'react-router-dom';

 

function Dashboard() {

  return (

    <div>

      <h2>Dashboard</h2>

      <nav>

        <ul>

          <li><Link to="/dashboard/overview">Overview</Link></li>

          <li><Link to="/dashboard/settings">Settings</Link></li>

        </ul>

      </nav>

 

      <Route path="/dashboard/overview" component={Overview} />

      <Route path="/dashboard/settings" component={Settings} />

    </div>

  );

}

 

function Overview() {

  return <h3>Overview Section</h3>;

}

 

function Settings() {

  return <h3>Settings Section</h3>;

}

 

export default Dashboard;

2.  Modify App.js to include the Dashboard route:

javascript

Copy code

import React from 'react';

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

import Dashboard from './Dashboard';

 

function App() {

  return (

    <Router>

      <div>

        <nav>

          <ul>

            <li><Link to="/dashboard">Dashboard</Link></li>

          </ul>

        </nav>

 

        <Route path="/dashboard" component={Dashboard} />

      </div>

    </Router>

  );

}

 

export default App;

Explanation:

  • The Dashboard component contains two nested routes: Overview and Settings.
  • Inside the Dashboard, the Route components display content based on the sub-path.
  • The main route (/dashboard) shows the Dashboard component with navigation links for the sub-routes.

Assignment 4: Redirecting to a New Route

Task:

Create a Redirect from the Home page to the About page after 3 seconds. Use Redirect from React Router.

Solution:

1.  Modify the Home Component:

javascript

Copy code

import React, { useEffect } from 'react';

import { Redirect } from 'react-router-dom';

 

function Home() {

  const [redirect, setRedirect] = React.useState(false);

 

  useEffect(() => {

    const timer = setTimeout(() => {

      setRedirect(true);

    }, 3000);

    return () => clearTimeout(timer);

  }, []);

 

  if (redirect) {

    return <Redirect to="/about" />;

  }

 

  return <h2>Home Page - Redirecting to About page...</h2>;

}

 

export default Home;

2.  Modify App.js to include the About page:

javascript

Copy code

import React from 'react';

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

import Home from './Home';

import About from './About';

 

function App() {

  return (

    <Router>

      <div>

        <nav>

          <ul>

            <li><Link to="/">Home</Link></li>

            <li><Link to="/about">About</Link></li>

          </ul>

        </nav>

 

        <Route path="/" exact component={Home} />

        <Route path="/about" component={About} />

      </div>

    </Router>

  );

}

 

export default App;

Explanation:

  • The Home component uses the Redirect component to navigate to the About page after 3 seconds.
  • A state redirect is used to trigger the redirect after a timer of 3 seconds set by setTimeout.
  • useEffect ensures that the timer is set when the component mounts.

Assignment 5: Using useHistory for Programmatic Navigation

Task:

Create a button on the Home page that, when clicked, will navigate the user to the About page using useHistory.

Solution:

1.  Modify the Home Component to Use useHistory:

javascript

Copy code

import React from 'react';

import { useHistory } from 'react-router-dom';

 

function Home() {

  const history = useHistory();

 

  const goToAbout = () => {

    history.push('/about');

  };

 

  return (

    <div>

      <h2>Home Page</h2>

      <button onClick={goToAbout}>Go to About</button>

    </div>

  );

}

 

export default Home;

2.  Modify App.js to include the About page:

javascript

Copy code

import React from 'react';

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

import Home from './Home';

import About from './About';

 

function App() {

  return (

    <Router>

      <div>

        <Route path="/" exact component={Home} />

        <Route path="/about" component={About} />

      </div>

    </Router>

  );

}

 

export default App;

Explanation:

  • useHistory hook is used to programmatically navigate between routes.
  • history.push('/about') triggers navigation to the About page when the button is clicked.

Conclusion

These assignments cover various React Router topics, including basic routing, dynamic routes, nested routes, redirects, and programmatic navigation. Each solution comes with clear explanations and step-by-step implementations to help beginners understand the concepts effectively.


Tags

Post a Comment

0Comments

Post a Comment (0)