Having trouble rendering components due to conflicts between React Router and Semantic UI React

Below is the code in my App.js:

import { useRecoilValue } from 'recoil';
import { authState } from './atoms/authAtom';
import { ToastContainer } from 'react-toastify';
import { ProtectedRoute } from './layout/ProtectedRoute';
import CourseDashboard from './features/course/CourseDashboard';
import { Route, Routes } from 'react-router-dom';
import NavBar from './features/nav/Navbar';
import { LoginPage } from './features/auth/LoginPage';

export const App = () => {
  const authentication = useRecoilValue(authState)

  return (
    <>
      <ToastContainer position='bottom-right' hideProgressBar />
      <NavBar />
      <Routes>
        <Route path='/courses' element={
          <ProtectedRoute user={authentication?.user} isAuthenticated={authentication?.isAuthenticated} redirectPath={'/login'}>
            <CourseDashboard />
          </ProtectedRoute>
        } />

        <Route path='/' element={
          <ProtectedRoute user={authentication?.user} isAuthenticated={authentication?.isAuthenticated} redirectPath={'/login'}>
            <CourseDashboard />
          </ProtectedRoute>
        } />

        <Route path='/login' element={<LoginPage />} />
      </Routes>
    </>
  )
}

This section pertains to index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
import { RecoilRoot } from 'recoil';
import { BrowserRouter } from 'react-router-dom';
import 'semantic-ui-css/semantic.min.css'
import './styles.css'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RecoilRoot>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </RecoilRoot>
  </React.StrictMode>
);

I am utilizing Recoil for state management, Semantic UI React for styling, and React Router DOM v6 for routing.

The issue I'm facing is that the NavBar component renders at the top of the page, but components like CourseDashboard or LoginPage below it do not render.

https://i.stack.imgur.com/M8kQN.png

This is what my login page looks like:

import { Container, Form, Input, Text } from "semantic-ui-react";

export const LoginPage = () => {
  return (
    <>
      <Form>
        <Input name="email" type="email" placeholder="Enter Email" />
        <Input name="password" placeholder="Enter Password" type="password" />
      </Form>
    </>
  );
};

If I remove the Semantic UI part and just use basic HTML elements like this:

import { Container, Form, Input, Text } from "semantic-ui-react";

export const LoginPage = () => {
  return (
    <>
      {/* <Form>
        <Input name="email" type="email" placeholder="Enter Email" />
        <Input name="password" placeholder="Enter Password" type="password" />
      </Form> */}

      <h1>login</h1>
    </>
  );
};

With the above change, it renders as expected:

https://i.stack.imgur.com/YdGs7.png

I've been troubleshooting for hours but couldn't find a solution. Can someone help? Thanks in advance.

Edit:

Considering a suggestion, upon checking the DOM it appears that the LoginPage component does render, but it's positioned behind the NavBar component even though they are separate. How can I separate them and have the LoginPage component render below the NavBar?

https://i.stack.imgur.com/hboaY.png

This is the NavBar Component:

import React from "react";
import { Menu, Container } from "semantic-ui-react";
import { useRecoilValue } from "recoil";
import { authState } from "../../atoms/authAtom";
import { NavLink } from "react-router-dom";
import { SignedInMenu } from "./SignedInMenu";

export default function NavBar() {
  const authentication = useRecoilValue(authState);
  console.log(authentication);

  return (
    <Menu inverted fixed="top">
      <Container>
        <Menu.Item as={NavLink} exact to="/" header>
          <img
            src="/assets/logo.jpg"
            alt="logo"
            style={{ marginRight: "15px" }}
          />
          Bhaktivedanta Vedic Academy
        </Menu.Item>

        <Menu.Item name="Courses" as={NavLink} to="/courses" />

        {authentication?.isAuthenticated && <SignedInMenu />}
      </Container>
    </Menu>
  );
}

Answer №1

Using fixed positioning in the NavBar component removes it from the normal flow of the DOM, causing other elements to render underneath it from the top of the view. One way to fix this is by adding padding-top to each routed component you're rendering, or alternatively, create a layout route component that includes the NavBar and an Outlet within a div element with the necessary padding-top CSS rule applied. The height of the NavBar is approximately 44px, so any value close to this will suffice.

For instance:

import { Outlet } from "react-router-dom";
import NavBar from "./features/nav/NavBar";

const AppLayout = () => (
  <div className="app-layout">
    <NavBar />
    <Outlet />
  </div>
);
<Routes>
  <Route element={<AppLayout />}> // <-- Layout wraps all routes
    <Route
      element={
        <ProtectedRoute
          user={authentication?.user}
          isAuthenticated={authentication?.isAuthenticated}
          redirectPath={"/login"}
        />
      }
    >
      <Route path="/courses" element={<CourseDashboard />} />
      <Route path="/" element={<CourseDashboard />} />
    </Route>
    <Route path="/login" element={<LoginPage />} />
  </Route>
</Routes>
.app-layout {
  padding-top: 3.25rem; /* 45px from base 14px font size */
}

https://i.stack.imgur.com/RVWhU.png https://i.stack.imgur.com/6Nogg.png https://i.stack.imgur.com/yQWgO.png

https://codesandbox.io/s/xenodochial-microservice-3dwowc?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

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

Modern design featuring soft borders that blend into the background

I am in the process of bringing a unique webpage layout to life. The design is a bit unconventional, and I'm not sure if it's feasible. Essentially, I plan to have a fixed-width content box of 900px positioned in the center of the page body. I ai ...

The disabled button is not displayed when it is disabled

Encountering an issue specific to Chrome version 60.0.3112.90 where changing the disabled attribute of a button causes it to disappear. A minimal, complete, and verifiable example has been prepared wherein clicking the + button toggles the disabled attri ...

Regular Expression - Invalid character detected in output

I'm currently in the process of developing a function to verify if a field is deemed acceptable based on a specific character set. In case it doesn't meet the criteria, I aim to determine and communicate which characters are not permitted. While ...

Unable to identify collision in JavaScript's 3D environment

I'm currently using three.js to develop a simulation of Brownian Motion, but I've hit a roadblock when it comes to getting the tiny molecules to collide with each other. This is the snippet I have at the moment: function intersects(sphere, other ...

How can I make my div change color when the check-box is selected?

I have a dynamic table in my web application that is populated with data from a database. Each row in the table represents multiple time slots for a specific date. I am working on a feature where the background color of a time block can be changed if a che ...

Implementing RequireJS Singleton pattern with Web Workers

I'm currently working on a JavaScript project that utilizes the latest version of RequireJS. One of the modules I am defining is chessWorker, as shown below: var worker; define("chessWorker", ["jquery", "messageListener"], function($, listener) { ...

Node.js process.exec() function allows you to asynchronously spawn a subprocess

After writing the code, I ran it and found that the terminal was unresponsive with no output, causing the program to be stuck. var util=require('util') var exec=require('child_process').exec; exec('iostat 5',function(err,stdo ...

Having trouble registering an uninstalled web hook in a Shopify React app

// I encountered an issue when trying to register an uninstalled app webhook. The code I have used for registering other hooks is functioning correctly, but I am facing an error specifically with the uninstalled webhook registration. const registrationU ...

What could be causing me to receive [object Object] when making an axios GET request?

I am currently developing a react-express application and pulling data from a SQLite3 database. The data structure is as follows: [ { id:1, name: 'henry', photo: '/Photos/dog1.jpg' }, { id:1, ...

VueRouter child route with trailing slash after default

VueRouter automatically includes a trailing slash before the child route's path. Consider this example of a route configuration: const routes = [ path: '/home', components: { default: HomeBase }, children: [ ...

jQuery - Modify Turn.js to exclusively implement the page Peel effect

I am attempting to implement the peel effect from turn.js into my code, where hovering over the bottom right corner of the page causes it to peel slightly and appear as if it is bending upwards. I specifically want only the peel effect and not the entire ...

Enhanced SSL connectivity features in Meteor version 1.8.1

My development server is running on localhost (Windows 10 Pro x64 build 1903) and will eventually be moved to the production environment (Galaxy). To enable authentication through Facebook or Google, HTTPS is required. I configured Nourharidy Meteor SSL on ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Navigate to a fresh web page without encountering any script loading issues

I am currently working on a web application that loads new pages without requiring the browser to reload. While some pages load perfectly fine, others are causing errors due to missing scripts. The code snippet below is used to load a new page: function lo ...

Experiencing difficulty with setting up the ReactJS pagination component

Each time I click on a page number, the maximum size of the pages is returned as a handler parameter (for example, clicking on 2 returns 4). What could be causing this issue? UPDATE class PagingControl extends React.Component{ constructor(props) { ...

Using dynamic tag names within React JSX can greatly enhance the flexibility and

I'm working on creating a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is determined by a prop. Here is how I attempted to approach it: <h{this.props.level}>Hello</h{this.props.level}> My expected out ...

Exploring the distinctions between ajax, await, async, and

English is not my strong suit, so please bear with me if my writing seems odd. We have discovered two methods for transitioning from asynchronous ajax calls to synchronous ones. Using async: false Utilizing await Both achieve the same outcome, but I am ...

Retrieve the nested value of an object using the specified key field

When using the DataGrid component from material-ui to display my data in a table, I encountered an issue with accessing nested values. Specifically, I have a nested array of data but am unable to retrieve the nested value within the datagrid using the key ...

Steps for placing an image within the boundary of a rectangular div

My div has a width of approximately 730px and a height of 50px. I am looking to place an image at the bottom of the div, exactly where its height ends - after 50px. I have been considering a query to append the image at the bottom. One solution could be ...