Assignment s Of Day 15 - Nested Routing and Route Parameters

Rashmi Mishra
0

Assignment s Of Day 15 - Nested Routing and Route Parameters

 

Assignment 1: Create a Nested Routing Structure for a Blog Application

Objective: Build a simple blog application with nested routes for viewing individual blog posts.

 

Step 1: Set Up Your React Application

Create a new React application using Create React App:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npx create-react-app blog-app

cd blog-app

npm install react-router-dom

Step 2: Create the Components

Create the following components in the src folder:

Home.js

Blog.js

Post.js

Home.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Home() {

  return (

    <div>

      <h1>Welcome to the Blog</h1>

      <Link to="/blog">Go to Blog</Link>

    </div>

  );

}

 

export default Home;

Blog.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Post from './Post';

 

function Blog() {

  const posts = [

    { id: 1, title: 'First Post' },

    { id: 2, title: 'Second Post' },

  ];

 

  return (

    <div>

      <h1>Blog</h1>

      <ul>

        {posts.map(post => (

          <li key={post.id}>

            <Link to={`/blog/${post.id}`}>{post.title}</Link>

          </li>

        ))}

      </ul>

      <Switch>

        <Route path="/blog/:postId" component={Post} />

      </Switch>

    </div>

  );

}

 

export default Blog;

Post.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Post() {

  const { postId } = useParams();

  return (

    <div>

      <h2>Post ID: {postId}</h2>

      <p>This is the content of post {postId}.</p>

    </div>

  );

}

 

export default Post;

Step 3: Set Up Routing in App.js

Modify App.js to include routing:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Home from './Home';

import Blog from './Blog';

 

function App() {

  return (

    <Router>

      <Switch>

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

        <Route path="/blog" component={Blog} />

      </Switch>

    </Router>

  );

}

 

export default App;

Step 4: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The Home component provides a link to the Blog component.

The Blog component lists all blog posts and uses nested routing to display individual posts based on the postId parameter.

The Post component retrieves the postId from the URL and displays the corresponding content.

Assignment 2: Create a User Profile Application with Dynamic Routing

Objective: Build a user profile application that displays user details based on the user ID in the URL.

 

Step 1: Set Up Your React Application

Create a new React application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npx create-react-app user-profile-app

cd user-profile-app

npm install react-router-dom

Step 2: Create the Components

Create the following components in the src folder:

Home.js

User List.js

User Profile.js

Home.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Home() {

  return (

    <div>

      <h1>Welcome to User Profiles</h1>

      <Link to="/users">View Users</Link>

    </div>

  );

}

 

export default Home;

User List.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import UserProfile from './User Profile';

 

function UserList() {

  const users = [

    { id: 1, name: 'Alice' },

    { id: 2, name: 'Bob' },

  ];

 

  return (

    <div>

      <h1>User List</h1>

      <ul>

        {users.map(user => (

          <li key={user.id}>

            <Link to={`/users/${user.id}`}>{user.name}</Link>

          </li>

        ))}

      </ul>

      <Switch>

        <Route path="/users/:userId" component={User Profile} />

      </Switch>

    </div>

  );

}

 

export default UserList;

User Profile.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function UserProfile() {

  const { userId } = useParams();

  return (

    <div>

      <h2>User Profile</h2>

      <p>User ID: {userId}</p>

      {/* Here you can fetch and display user data based on userId */}

    </div>

  );

}

 

export default UserProfile;

Step 3: Set Up Routing in App.js

Modify App.js to include routing:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Home from './Home';

import UserList from './User List';

 

function App() {

  return (

    <Router>

      <Switch>

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

        <Route path="/users" component={User List} />

      </Switch>

    </Router>

  );

}

 

export default App;

Step 4: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The Home component provides a link to the User List component.

The User List component displays a list of users and uses nested routing to show individual user profiles based on the userId parameter.

The User Profile component retrieves the userId from the URL and can be extended to fetch and display user data.

Assignment 3: Fetching Data Based on Route Parameters

Objective: Extend the user profile application to fetch user data from an API based on the user ID.

 

Step 1: Set Up Your React Application

Use the previous user profile application setup.

Step 2: Modify UserProfile.js to Fetch Data

Update the User Profile.js component to fetch user data:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React, { useEffect, useState } from 'react';

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

 

function UserProfile() {

  const { userId } = useParams();

  const [userData, setUser Data] = useState(null);

 

  useEffect(() => {

    // Fetch user data from an API

    fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)

      .then(response => response.json())

      .then(data => setUser Data(data))

      .catch(error => console.error('Error fetching user data:', error));

  }, [userId]);

 

  return (

    <div>

      <h2>User Profile</h2>

      {userData ? (

        <div>

          <p>User ID: {userData.id}</p>

          <p>Name: {userData.name}</p>

          <p>Email: {userData.email}</p>

          <p>Phone: {userData.phone}</p>

          {/* Display other user data as needed */}

        </div>

      ) : (

        <p>Loading user data...</p>

      )}

    </div>

  );

}

 

export default UserProfile;

Step 3: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The User Profile component now fetches user data from a placeholder API based on the userId parameter.

The useEffect hook is used to make the API call when the component mounts, and the user data is displayed once it is fetched.

Conclusion

These assignments provide a hands-on approach to understanding nested routing and route parameters in React applications. By completing these tasks, you will gain practical experience in setting up routing, creating dynamic components, and fetching data based on user interactions. Feel free to expand on these assignments by adding more features or styling to enhance your applications! ### Assignment 4: Create a Nested Routing Structure for an E-commerce Application

 

Objective: Build a simple e-commerce application with nested routes for viewing individual product details.

 

Step 1: Set Up Your React Application

Create a new React application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npx create-react-app ecommerce-app

cd ecommerce-app

npm install react-router-dom

Step 2: Create the Components

Create the following components in the src folder:

Home.js

Products.js

ProductDetails.js

Home.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Home() {

  return (

    <div>

      <h1>Welcome to the E-commerce Store</h1>

      <Link to="/products">View Products</Link>

    </div>

  );

}

 

export default Home;

Products.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import ProductDetails from './ProductDetails';

 

function Products() {

  const products = [

    { id: 1, name: 'Product 1' },

    { id: 2, name: 'Product 2' },

  ];

 

  return (

    <div>

      <h1>Products</h1>

      <ul>

        {products.map(product => (

          <li key={product.id}>

            <Link to={`/products/${product.id}`}>{product.name}</Link>

          </li>

        ))}

      </ul>

      <Switch>

        <Route path="/products/:productId" component={ProductDetails} />

      </Switch>

    </div>

  );

}

 

export default Products;

ProductDetails.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function ProductDetails() {

  const { productId } = useParams();

  return (

    <div>

      <h2>Product Details</h2>

      <p>Details for Product ID: {productId}</p>

      {/* Here you can fetch and display product data based on productId */}

    </div>

  );

}

 

export default ProductDetails;

Step 3: Set Up Routing in App.js

Modify App.js to include routing:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Home from './Home';

import Products from './Products';

 

function App() {

  return (

    <Router>

      <Switch>

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

        <Route path="/products" component={Products} />

      </Switch>

    </Router>

  );

}

 

export default App;

Step 4: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The Home component provides a link to the Products component.

The Products component lists all products and uses nested routing to display individual product details based on the productId parameter.

The ProductDetails component retrieves the productId from the URL and can be extended to fetch and display product data.

Assignment 5: Fetching Product Data Based on Route Parameters

Objective: Extend the e-commerce application to fetch product data from an API based on the product ID.

 

Step 1: Set Up Your React Application

Use the previous e-commerce application setup.

Step 2: Modify ProductDetails.js to Fetch Data

Update the ProductDetails.js component to fetch product data:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React, { useEffect, useState } from 'react';

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

 

function ProductDetails() {

  const { productId } = useParams();

  const [productData, setProductData] = useState(null);

 

  useEffect(() => {

    // Fetch product data from an API

    fetch(`https://fakestoreapi.com/products/${productId}`)

      .then(response => response.json())

      .then(data => setProductData(data))

      .catch(error => console.error('Error fetching product data:', error));

  }, [productId]);

 

  return (

    <div>

      <h2>Product Details</h2>

      {productData ? (

        <div>

          <h3>{productData.title}</h3>

          <p>Price: ${productData.price}</p>

          <p>{productData.description}</p>

          <img src={productData.image} alt={productData.title} />

        </div>

      ) : (

        <p>Loading product data ...</p>

      )}

    </div>

  );

}

 

export default ProductDetails;

Step 3: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The ProductDetails component now fetches product data from a placeholder API based on the productId parameter.

The useEffect hook is used to make the API call when the component mounts, and the product data is displayed once it is fetched.

Conclusion

These assignments provide a comprehensive approach to understanding nested routing and route parameters in React applications. By completing these tasks, you will gain practical experience in setting up routing, creating dynamic components, and fetching data based on user interactions. Feel free to expand on these assignments by adding more features or styling to enhance your applications! ### Assignment 6: Create a Nested Routing Structure for a Recipe Application

 

Objective: Build a simple recipe application with nested routes for viewing individual recipe details.

 

Step 1: Set Up Your React Application

Create a new React application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npx create-react-app recipe-app

cd recipe-app

npm install react-router-dom

Step 2: Create the Components

Create the following components in the src folder:

Home.js

Recipes.js

RecipeDetails.js

Home.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Home() {

  return (

    <div>

      <h1>Welcome to the Recipe App</h1>

      <Link to="/recipes">View Recipes</Link>

    </div>

  );

}

 

export default Home;

Recipes.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import RecipeDetails from './RecipeDetails';

 

function Recipes() {

  const recipes = [

    { id: 1, name: 'Spaghetti Bolognese' },

    { id: 2, name: 'Chicken Curry' },

  ];

 

  return (

    <div>

      <h1>Recipes</h1>

      <ul>

        {recipes.map(recipe => (

          <li key={recipe.id}>

            <Link to={`/recipes/${recipe.id}`}>{recipe.name}</Link>

          </li>

        ))}

      </ul>

      <Switch>

        <Route path="/recipes/:recipeId" component={RecipeDetails} />

      </Switch>

    </div>

  );

}

 

export default Recipes;

RecipeDetails.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function RecipeDetails() {

  const { recipeId } = useParams();

  return (

    <div>

      <h2>Recipe Details</h2>

      <p>Details for Recipe ID: {recipeId}</p>

      {/* Here you can fetch and display recipe data based on recipeId */}

    </div>

  );

}

 

export default RecipeDetails;

Step 3: Set Up Routing in App.js

Modify App.js to include routing:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Home from './Home';

import Recipes from './Recipes';

 

function App() {

  return (

    <Router>

      <Switch>

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

        <Route path="/recipes" component={Recipes} />

      </Switch>

    </Router>

  );

}

 

export default App;

Step 4: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The Home component provides a link to the Recipes component.

The Recipes component lists all recipes and uses nested routing to display individual recipe details based on the recipeId parameter.

The RecipeDetails component retrieves the recipeId from the URL and can be extended to fetch and display recipe data.

Assignment 7: Fetching Recipe Data Based on Route Parameters

Objective: Extend the recipe application to fetch recipe data from an API based on the recipe ID.

 

Step 1: Set Up Your React Application

Use the previous recipe application setup.

Step 2: Modify RecipeDetails.js to Fetch Data

Update the RecipeDetails.js component to fetch recipe data:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React, { useEffect, useState } from 'react';

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

 

function RecipeDetails() {

  const { recipeId } = useParams();

  const [recipeData, setRecipeData] = useState(null);

 

  useEffect(() => {

    // Fetch recipe data from an API

    fetch(`https://api.example.com/recipes/${recipeId}`)

      .then(response => response.json())

      .then(data => setRecipeData(data))

      .catch(error => console.error('Error fetching recipe data:', error));

  }, [recipeId]);

 

  return (

    <div>

      <h2>Recipe Details</h2>

      {recipeData ? (

        <div>

          <h3>{recipeData.title}</h3>

          <p>Ingredients: {recipeData.ingredients.join(', ')}</p>

          <p>Instructions: {recipeData.instructions}</p>

          {/* Display other recipe data as needed */}

        </div>

      ) : (

        <p>Loading recipe data...</p>

      )}

 </div>

  );

}

 

export default RecipeDetails;

Step 3: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The RecipeDetails component now fetches recipe data from a placeholder API based on the recipeId parameter.

The useEffect hook is used to make the API call when the component mounts, and the recipe data is displayed once it is fetched.

Conclusion

These assignments provide a comprehensive approach to understanding nested routing and route parameters in React applications. By completing these tasks, you will gain practical experience in setting up routing, creating dynamic components, and fetching data based on user interactions. Feel free to expand on these assignments by adding more features or styling to enhance your applications! ### Assignment 8: Create a Nested Routing Structure for a Movie Application

 

Objective: Build a simple movie application with nested routes for viewing individual movie details.

 

Step 1: Set Up Your React Application

Create a new React application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npx create-react-app movie-app

cd movie-app

npm install react-router-dom

Step 2: Create the Components

Create the following components in the src folder:

Home.js

Movies.js

MovieDetails.js

Home.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function Home() {

  return (

    <div>

      <h1>Welcome to the Movie App</h1>

      <Link to="/movies">View Movies</Link>

    </div>

  );

}

 

export default Home;

Movies.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import MovieDetails from './MovieDetails';

 

function Movies() {

  const movies = [

    { id: 1, title: 'Inception' },

    { id: 2, title: 'Interstellar' },

  ];

 

  return (

    <div>

      <h1>Movies</h1>

      <ul>

        {movies.map(movie => (

          <li key={movie.id}>

            <Link to={`/movies/${movie.id}`}>{movie.title}</Link>

          </li>

        ))}

      </ul>

      <Switch>

        <Route path="/movies/:movieId" component={MovieDetails} />

      </Switch>

    </div>

  );

}

 

export default Movies;

MovieDetails.js:

 

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

 

function MovieDetails() {

  const { movieId } = useParams();

  return (

    <div>

      <h2>Movie Details</h2>

      <p>Details for Movie ID: {movieId}</p>

      {/* Here you can fetch and display movie data based on movieId */}

    </div>

  );

}

 

export default MovieDetails;

Step 3: Set Up Routing in App.js

Modify App.js to include routing:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React from 'react';

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

import Home from './Home';

import Movies from './Movies';

 

function App() {

  return (

    <Router>

      <Switch>

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

        <Route path="/movies" component={Movies} />

      </Switch>

    </Router>

  );

}

 

export default App;

Step 4: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The Home component provides a link to the Movies component.

The Movies component lists all movies and uses nested routing to display individual movie details based on the movieId parameter.

The MovieDetails component retrieves the movieId from the URL and can be extended to fetch and display movie data.

Assignment 9: Fetching Movie Data Based on Route Parameters

Objective: Extend the movie application to fetch movie data from an API based on the movie ID.

 

Step 1: Set Up Your React Application

Use the previous movie application setup.

Step 2: Modify MovieDetails.js to Fetch Data

Update the MovieDetails.js component to fetch movie data:

jsx

 

Verify

 

Open In Editor

Edit

Copy code

import React, { useEffect, useState } from 'react';

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

 

function MovieDetails() {

  const { movieId } = useParams();

  const [movieData, setMovieData] = useState(null);

 

  useEffect(() => {

    // Fetch movie data from an API

    fetch(`https://api.example.com/movies/${movieId}`)

      .then(response => response.json())

      .then(data => setMovieData(data))

      .catch(error => console.error('Error fetching movie data:', error));

  }, [movieId]);

 

  return (

    <div>

      <h2>Movie Details</h2>

      {movieData ? (

        <div>

          <h3>{movieData.title}</h3>

          <p>Release Date: {movieData.releaseDate}</p>

          <p>Overview: {movieData.overview}</p>

          <img src={movieData.posterPath} alt={movieData.title} />

        </div>

      ) : (

        <p>Loading movie data...</p>

      )}

    </div>

  );

}

 

export default MovieDetails;

Step 3: Run Your Application

Start your application:

bash

 

Verify

 

Open In Editor

Edit

Copy code

npm start

Explanation:

 

The MovieDetails component now fetches movie data from a placeholder API based on the movieId parameter.

The useEffect hook is used to make the API call when the component mounts, and the movie data is displayed once it is fetched.

Conclusion

These assignments provide a comprehensive approach to understanding nested routing and route parameters in React applications. By completing these tasks, you will gain practical experience in setting up routing, creating dynamic components, and fetching data based on user interactions. Feel free to expand on these assignments by adding more features or styling to enhance your applications!

 

You

 

WRITE 100 no of MCQs only FROM ABOVE CONCEPT with explanation

 

BLACKBOXAI

 

Here are 100 multiple-choice questions (MCQs) based on the concepts of nested routing and route parameters in React applications, along with explanations for the correct answers.

 


Tags

Post a Comment

0Comments

Post a Comment (0)