skip to Main Content

I am using the latest React-Router version 6. I am using createBrowseRouter using createRoutesFromElements to route and link my pages for a one page portfolio website, but when I click on the nav-link to scroll down to specified element section/page it does not work, the url does show that is has changed but it does not move to that section.

This is the code on the App.jsx file

import './App.css'
import './index.css'
import {
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider
} from 'react-router-dom';
import Navbar from './Components/Navbar'
import Home from './Components/Home';
import About from './Components/About';
import TechnicalSkills from './Components/TechnicalSkills';
import Projects from './Components/Projects';
import Contact from './Components/Contact';
import ContactForm from './Components/ContactForm';
import Footer from './Components/Footer';

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<Home />}>
      <Route path="Navbar" element={<Navbar />} />
      <Route path="about" element={<About />} />
      <Route path="technicalskills" element={<TechnicalSkills />} />
      <Route path="projects" element={<Projects />} />
      <Route path="contactForm" element={<ContactForm />} />
      <Route path="contact" element={<Contact />} />
    </Route>
  ) 
)

// eslint-disable-next-line react/prop-types
function App({Route}) {
  return (
    <>
      <Navbar />
      <Home />
      <About />
      <TechnicalSkills />
      <Projects />
      <Contact />
      <Footer />
    </>
  );
}

<RouterProvider router={router} />

export default App;

For the Navbar

import React from "react";
import {
  Navbar,
  Collapse,
  Typography,
  IconButton,
} from "@material-tailwind/react";
import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/outline";
import { Link } from "react-router-dom";

function NavList() {
  return (
    <ul className="my-2 flex flex-col gap-2 lg:mb-0 lg:mt-0 lg:flex-row lg:items-center lg:gap-6">
      <Typography
        as="li"
        variant="small"
        color="blue-gray"
        className="p-1 font-medium"
      >
        <Link to="/Home" className="hover:text-blue-500 transition-colors">
          Home
        </Link>
      </Typography>
      <Typography
        as="li"
        variant="small"
        color="blue-gray"
        className="p-1 font-medium"
      >
        <Link to="/about" className="hover:text-blue-500 transition-colors">
          About
        </Link>
      </Typography>
      <Typography
        as="li"
        variant="small"
        color="blue-gray"
        className="p-1 font-medium"
      >
       <Link to="/TechnicalSkills" className="hover:text-blue-500 transition-colors">
          Skills
        </Link>
      </Typography>
      <Typography
        as="li"
        variant="small"
        color="blue-gray"
        className="p-1 font-medium"
      >
        <Link to="/Projects" className="hover:text-blue-500 transition-colors">
          Projects
        </Link>
      </Typography>

<Typography
        as="li"
        variant="small"
        color="blue-gray"
        className="p-1 font-medium"
      >
         <Link to="/Contact" className="hover:text-blue-500 transition-colors">
          Contact
        </Link>
      </Typography>
    </ul>
  );
}
 
export default function NavbarSimple() {
  const [openNav, setOpenNav] = React.useState(false);
 
  const handleWindowResize = () =>
    window.innerWidth >= 1024 && setOpenNav(false);
 
  React.useEffect(() => {
    window.addEventListener("resize", handleWindowResize);
 
    return () => {
      window.removeEventListener("resize", handleWindowResize);
    };
  }, []);
 
  return (
    <Navbar className="mx-auto max-w-screen-xl px-6 py-3">
      <div className="flex items-center justify-between text-blue-gray-900">
        <Typography
          as="a"
          href="#"
          variant="h6"
          className="mr-4 cursor-pointer py-1.5"
        >
          Material Tailwind
        </Typography>
        <div className="hidden lg:block">
          <NavList />
        </div>
        <IconButton
          variant="text"
          className="ml-auto h-6 w-6 text-inherit hover:bg-transparent focus:bg-transparent active:bg-transparent lg:hidden"
          ripple={false}
          onClick={() => setOpenNav(!openNav)}
        >
          {openNav ? (
            <XMarkIcon className="h-6 w-6" strokeWidth={2} />
          ) : (
            <Bars3Icon className="h-6 w-6" strokeWidth={2} />
          )}
        </IconButton>
      </div>
      <Collapse open={openNav}>
        <NavList />
      </Collapse>
    </Navbar>
  );
}

Page Home

import { Button } from "@material-tailwind/react";
import DownloadForOfflineIcon from '@mui/icons-material/DownloadForOffline';
import GitHubIcon from '@mui/icons-material/GitHub';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import MailIcon from '@mui/icons-material/Mail';

function Home() {
  return (
    <div className=" home-component max-w-md mx-auto overflow-hidden md:max-w-2xl mt-6 mb-12 justify-center text-lg gap-2" >
     <div className="md:flex">
     <div className="md:p-8">
      <div className="uppercase tracking-wide text-2xl text-black font-semibold text-center leading-relaxed">Hi, I am</div>
       <p className="block mt-1 text-4xl leading-tight text-blachover:underline text-indigo-500 font-semibold mb-2 tracking-wide text-center">Jenise Lukhele</p>
       <p className="text-slate-200 text-black text-2xl font-semibold text-center mb-3">Fronted Developer</p>
       <div className="sm:flex text-center ml-5">
       <Button variant="outlined" size="sm" className='mt-6 me-2 items-center'>
       <span className="mr-1 md:font-size-md ">
       Resume
       </span>
       <a href="Hlobisile Lukhele resume (10).pdf" target="_blank" download="HlobisileLukhele Resume" >
       <DownloadForOfflineIcon className="sm" />
       </a>
        </Button>
        <Button variant="filled" size="md" className='mt-6 me-2'>
           Get In Touch
        </Button>
       </div>
    </div>
    <div className="flex mx-auto sm:justify-items-center ">
      <img className="Head-shot md:h-60 md:w-70 mb-4, lg:h-60 md:w-60 mb-4, sm:h-60 w-60 text-center  rounded-full object-cover object-center"src="public/images/head-shot image.png" alt="Head-shot image" />
    </div>
    </div>
    <div className='social-icons mt-2 mb-8 '>
      <div className="container-fluid text-left social-links gap-6 ml-16 fa-3xl ">
                <a href="https://www.linkedin.com/in/hlobisile-lukhele-8812b9183/" rel="noreferrer" target="_blank">
                    <LinkedInIcon style={{ color: "black",fontSize: "34px", margin:"5px"}} />                  
                </a>
                <a href="https://github.com/HlobisileLukhele" rel="noreferrer" target="_blank">
                      <GitHubIcon style={{ color: "black",fontSize: "34px", margin:"5px" }} />
                </a>

                <a href="https://[email protected]/" rel="noreferrer" target="_blank">
                      <MailIcon style={{ color: "black",fontSize: "34px", margin:"5px" }} />
                </a>

            </div>
    </div>
</div>
    );
}

export default Home;

About page

import React from 'react';
import { Typography } from "@material-tailwind/react";
import { Link } from 'react-router-dom';

function About() {
    return (
        <div id="about">
            <Typography variant="h4" color="blue-gray" className=" mb-6 mt-6 text-center font-serif">
            About 
          </Typography>
            <p className="mb-8 text-center ml-10 mr-10 whitespace-normal "> Frontend developer with a passion for coding and creating responsive and functional web applications.
               My journey in web development began when I enrolled in coding bootcamps to learn the necessary skills to become a developer.
               Since then, I have continued to learn and grow as a developer, and I am constantly exploring new technologies and techniques to improve my skills.
               When I'm not coding, I enjoy  going for jogs and exploring music.  </p>
        </div>
    );
}

export default About;

Project page

import {
  Card,
  CardHeader,
  CardBody,
  CardFooter,
  Typography,
  Button,
} from "@material-tailwind/react";
import GitHubIcon from '@mui/icons-material/GitHub';
import LanguageIcon from '@mui/icons-material/Language';
   
export default function Projects() {
  return (
    <div className="md:container md:mx-auto my-6 mb-10 gap-2 space-x-4">
      <Typography variant="h3" color="blue-gray" className="mb-4 mt-6 text-center font-serif">
        Projects
      </Typography>
      <div className="lg: grid grid-cols-1 md:grid-cols-3 gap-14 ">
        <div className="md:w-96 border-black">
          <Card className="mt-6">
            <CardHeader color="blue-gray" className="relative h-46">
              <img src="public/images/Bellabheka website.png" alt="card-image" />
            </CardHeader>
            <CardBody>
              <Typography variant="h5" color="blue-gray" className="mb-2 text-indigo-500 font-semibold ">
                Bellabheka Website
              </Typography>
              <Typography color="blue-gray">
                Bellabheka is a catering and decor company that provides services to all kinds of events around Durban.
              </Typography>
            </CardBody>
            <CardFooter className="pt-2">
            <div className="icons text-center">
              <a href="https://github.com/HlobisileLukhele/BellaBheka-Website-" target="_blank">
              <GitHubIcon />
              </a>
              <a href="https://bellabheksa-website.netlify.app/" target="_blank">
              <LanguageIcon />
              </a>
            </div>
            </CardFooter>
          </Card>
        </div>
    
        <div className=" md:w-96 border-black">
          <Card className="mt-6 space-x-4">
            <CardHeader color="blue-gray" className="relative h-46">
              <img src="public/images/Portfolio Website.jpeg" alt="card-image" />
            </CardHeader>
            <CardBody>
              <Typography variant="h5" color="blue-gray" className="mb-2 text-indigo-500 font-semibold ">
                Personal Portfolio
              </Typography>
              <Typography color="blue-gray">
                Personal portfolio website to showcase skills acquired and projects built along with the impacts it derives.
              </Typography>
            </CardBody>
            <CardFooter className="pt-2">
            <div className="icons text-center ">
              <a href="https://github.com/HlobisileLukhele/Portfolio" target="_blank">
              <GitHubIcon />
              </a>
              <LanguageIcon />
            </div>
            </CardFooter>
          </Card>
        </div>

        <div className="w-full md:w-96">
          <Card className="mt-6 border-black">
            <CardHeader color="blue-gray" className="relative h-46">
            <img src="public/images/Fruad Detector.jpeg" alt="card-image" />
            </CardHeader>
            <CardBody>
              <Typography variant="h5" color="blue-gray" className="mb-2 text-indigo-500 font-semibold">
                Fruad Detector
              </Typography>
              <Typography color="blue-gray">
              A application that checks for fraudulent activities by analyzing card transactions.
              </Typography>
            </CardBody>
            <CardFooter className="pt-5">
              <div className="icons text-center">
                <LanguageIcon />
              </div>
            </CardFooter>
          </Card>
        </div>
      </div>
    </div>
  );
}

I tried to use "/:id', according to the documentation but it still was not routing when I click the navlink.

2

Answers


  1. Issue

    The App component is rendering all the UI components directly instead of rendering the router and routes. In fact, the RouterProvider isn’t used inside any React component and I’m surprised you don’t have a syntax error for this dangling code snippet and any invariant errors rendering the Navbar outside a router.

    const router = createBrowserRouter(
      createRoutesFromElements(
        <Route path="/" element={<Home />}>
          <Route path="Navbar" element={<Navbar />} />
          <Route path="about" element={<About />} />
          <Route path="technicalskills" element={<TechnicalSkills />} />
          <Route path="projects" element={<Projects />} />
          <Route path="contactForm" element={<ContactForm />} />
          <Route path="contact" element={<Contact />} />
        </Route>
      );
    );
    
    // eslint-disable-next-line react/prop-types
    function App({ Route }) {
      return (
        <>
          <Navbar />          // <-- rendered directly!
          <Home />            // <-- rendered directly!
          <About />           // <-- rendered directly!
          <TechnicalSkills /> // <-- rendered directly!
          <Projects />        // <-- rendered directly!
          <Contact />         // <-- rendered directly!
          <Footer />
        </>
      );
    }
    
    <RouterProvider router={router} /> // <-- Not used!
    
    export default App;
    

    Solution

    The App component should render the RouterProvider and router component.

    You’ll likely want to render the Navbar and Footer outside the page routes though by using a Layout Route.

    Example:

    import {
      createBrowserRouter,
      createRoutesFromElements,
      Outlet,
      Route,
      RouterProvider
    } from 'react-router-dom';
    
    const AppLayout = () => (
      <>
        <Navbar />
        <Outlet />
        <Footer />
      </>
    );
    
    const router = createBrowserRouter(
      createRoutesFromElements(
        <Route element={<AppLayout />}>
          <Route index element={<Home />} />
          <Route path="about" element={<About />} />
          <Route path="technicalskills" element={<TechnicalSkills />} />
          <Route path="projects" element={<Projects />} />
          <Route path="contactForm" element={<ContactForm />} />
          <Route path="contact" element={<Contact />} />
        </Route>
      );
    );
    
    function App() {
      return <RouterProvider router={router} />;
    }
    
    export default App;
    
    Login or Signup to reply.
  2. In my latest SPA, I have done same thing with smooth-scroll and useEffect. You can try similar thing in your project

    export const scroll = new SmoothScroll('a[href*="#"]', {
      speed: 1000,
      speedAsDuration: true,
    });
    
    const App = () => {
      const [landingPageData, setLandingPageData] = useState({});
      useEffect(() => {
        setLandingPageData(JsonData);
      }, []);
    
    
    return (
        <>
          <BrowserRouter>
            <Routes>
              <Route
                exact
                path="/"
                element={
                  <div>
                    <Navigation />
                    <Home data={landingPageData.Home} />
                    <Navbar data={landingPageData.Navbar} />
                    <About data={landingPageData.About} />
                    <technicalskillsdata={landingPageData.technicalskills} />
                    <projects data={landingPageData.projects} />
                    <contactForm data={landingPageData.contactForm} />
                    <Contact data={landingPageData.Contact} />
                  </div>
                }
              />
              <Route path="*" element={<NotFound />} />
            </Routes>
          </BrowserRouter>
         
        </>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search