React Components Changing Route Leads to Empty Display

My current challenge involves setting up dynamic routing in my application to enable the viewing of products from different stores. Essentially, I am developing an app where users can add stores and browse through their items. I have implemented a dynamic route for the items component, allowing me to access each store's ID in the params and display the corresponding items. However, I encountered an issue where although I was able to retrieve the values in the component, the HTML content was not rendering, resulting in a blank page.

Below is the code snippet where I defined the route:

import React from "react";
import { Routes, Route } from "react-router-dom";
import StoresPreview from "../../components/StoresPreview/StoresPreview";
import ItemsMap from "../../components/Items/ItemsMap";

const StoresPage = () => {
  return (
    <>
      <Routes>
        <Route index element={<StoresPreview />} />
        <Route path=":number" element={<ItemsMap />} />
      </Routes>
    </>
  );
};

export default StoresPage;

Here is the component structure for the items map:

import React from "react";
import { useParams } from "react-router-dom";

const ItemsMap = () => {
  const { number } = useParams();
  console.log(number);
  return (
    <div>
      <h1>{`the id is ${number}`}</h1>
    </div>
  );
};

export default ItemsMap;

And this is how the main app component is set up:

import React from "react";
import { Routes, Route } from "react-router-dom";
import Navbar from "./components/NavbarWithDrawer/NavBar";
import HomePage from "./components/Home/Home";
import AdminSignIn from "./components/AdminSignIn/AdminSignIn";
import StoresPage from "./pages/StoresPage/StoresPage";

const App = () => {
  return (
    <>
      <Routes>
        <Route path="/" element={<Navbar />}>
          <Route index element={<HomePage />} />
          <Route path="stores/*" element={<StoresPage />} />
          <Route path="signin" element={<AdminSignIn />} />
        </Route>
      </Routes>
    </>
  );
};

export default App;

Despite attempting to add an outlet to StoresPreview in hopes of rendering the ItemsMap HTML, it did not yield the desired outcome.

Answer №1

It seems like your code is functioning correctly, and the page is not blank. The issue lies in the fact that the "this is the itemsMap" content of the ItemsMap component is displayed below the app header bar Navbar.

https://i.sstatic.net/ozbif.png

To resolve this, you can add a CSS rule of padding-top: 64px; (the height of the app bar component) to the container div element to move the content down into view.

For example:

const ItemsMap = () => {
  const { number } = useParams();

  return (
    <div style={{ paddingTop: "64px"}}>
      <h1>The id is {number}</h1>
    </div>
  );
};

https://i.sstatic.net/pfsev.png

Keep in mind that this only resolves the issue for the specific ItemsMap component. It would be better to apply this padding in the parent layout route component where the Outlet is rendered.

For instance:

export default function Navbar() {
  ...

  return (
    <>
      <Box sx={{ display: "flex" }}>
        <CssBaseline />
        <AppBar position="fixed" open={open}>
          ...
        </AppBar>
        <Drawer ... >
          ...
        </Drawer>
      </Box>
      <div style={{ paddingTop: "64px"}}> {/* Apply padding here */}
        <Outlet />
      </div>
    </>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing HTML5 Video Autoplay with AngularJS ng-show: A Comprehensive Guide

How can I implement a video using the HTML5 video tag with autoplay in an AngularJS web application? I attempted to use the following code: <video ng-show="condition" autoplay ng-src="{{video.src}}"></video> Upon loading the web application, ...

Two CSS Issues - One specific to mobile devices, the other unique to Chrome browser

Having trouble with the top banner not stretching all the way on iPhone. Any solutions? Here's a screenshot for reference: Below is the CSS applied to the div: #banner { background-color: #F7F7F7; background-size: cover; box-shadow: 0 0 ...

Opening a window in ExtJS when another window is already open

It seems like I'm having trouble opening a new window on top of another window that is already open in ExtJS 6. I have tried setting the model to true and bringToFront to true, but unfortunately, neither of them is working as expected. https://i.sstat ...

Ways to test the onClick event for firing a file input programmatically

I am a beginner when it comes to testing. My main goal is to verify if my onClick function was executed correctly. The purpose of the onClick function is to trigger the file input programmatically. const Component = () => { const onBtnClick = (e: Sy ...

Integrate the dateFilter function into a service within an AngularJS application

Is there a way to include filters in AngularJs services? I've been experimenting app.factory('educationService', [function($rootScope, $filter) { // ..... Some code // What I want console.log(dateFilter(new Date(), 'yyyy ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

How can I resolve the vertical adjustment issue of Bootstrap 5 input group on mobile devices?

My current issue involves using Bootstrap 5.2.3 to create an input group that displays a set of spans with the ".input-group-text" class alongside inputs with the ".form-control" class. While this setup works well on a computer screen, it does not adjust c ...

How can user data be logged in ASP.Net Core when a check box is selected?

Struggling to discover a way to secretly log user information such as their username when a checkbox is selected. The goal is to capture this data without the user's knowledge. Here is the code: This checkbox is a custom switch from MDB <div> ...

Error with replacing regular expressions in IE11 for the variable $0

Having both a string and a message: str = "Test $0 $1 $2"; message = "Hi %2 Hello %2" ; The goal is to replace all occurrences of %2 with str in the message using RegExp, like so: message = message.replace(new RegExp("%2" , "g"), str); While this works ...

What are all the different methods I can use to transfer element A to element B, and what are those methods?

While experimenting with Jquery, I encountered a roadblock and now have this question in mind. I wish to enclose all the anchor elements within a newly created div element. <td class="cont-mod-none-options" valign="top" align="right"> <a hr ...

Prevent sluggish script performance using GreaseMonkey

When I go to a certain website, there is an external script that loads very slowly, causing the page to be almost unusable at times. While disabling the script helps a bit, it means losing out on some important functionality. I'm wondering if there i ...

Is using Javascript objects a better alternative to Redux?

I'm in the process of creating my initial application with React and have opted to integrate Redux into it. Since incorporating Redux, it appears that setting a component state to a basic global JavaScript object would be a simpler approach. I unders ...

Steps for importing a Java project into Eclipse and configuring it to run on a Tomcat server

I need guidance on how to import an external project into a Tomcat server in order to view the output in a browser. The project is an online banking system developed using JSP, AJAX, and JavaScript. ...

Navigating the FormSpree redirect: Tips and tricks

I recently set up my website on Github Pages and wanted to integrate a free contact form from FormSpree. However, I encountered an issue where after submitting the form, it redirected to a different website, which was not ideal. After researching online, I ...

Using styled-components to enhance an existing component by adding a new prop for customization of styles

I am currently using styled-components to customize the styling of an existing component, specifically ToggleButton from material ui. However, I want my new component to include an additional property (hasMargin) that will control the style: import {Toggle ...

The issue of useEffect triggering twice is caused by React router redirection

In my route setup, I have the following configuration: <Route path={`list`} element={<ListPage />}> <Route path={`sidePanel1`} element={<SidePanel1 />} /> <Route path={`sidePanel2`} element={<SidePanel2 />} /> < ...

Perform subtraction operation between two arrays of objects in Javascript

Hey there, I could use some guidance on the best method for subtracting values between two arrays of objects. In my scenario (backend), I retrieve data on Products from mongodb, and I also fetch Trolley data from MySql. What I'm attempting to achieve ...

Align the image and text vertically within the <ul> tag

I'm trying to center-align the items in the navbar. https://i.stack.imgur.com/FmDYS.png Although the image looks centered, I believe it's because its size is stretching the navbar. How can I achieve this without changing the size of the picture ...

The left-floating elements are only partially functional

I recently encountered an issue with my HTML page that features a basic image gallery enhanced by lightboxes (fancybox). The images are meant to align left, with the first row containing three images and the second row containing two. <div class="image ...

Using the $.each and $.getJSON functions to capture a list of website links

Upon transforming an array of names into a list of URL links for online and offline users, while using only names for closed accounts, the $.map method along with the .getJSON method is employed. The goal is to iterate through each element using the $.each ...