Home > Back-end >  React Router Link Element Breaking Page
React Router Link Element Breaking Page

Time:08-26

I have been working on a personal project and recently learned react and packages. I have been looking the past few days at how to fix a problem I have been having with the Link component in React Router but cant find anyone with my problem. Let me begin by saying that I have everything installed correctly and nothing should be conflicting with it, I followed the documentation closely. Essentially when I use <Link> in my code the entirety of the header doesn't display and I get a blank page with no errors. I tried replacing link with <a> and <div> tags and everything shows up fine but just not with the <Link>

Here is the problem code.

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

const NavBar = () => {
  return (
    <header>
      <div  id="pageHeader">
        <div ></div> {/* spacer for begining of header */}

        {/* code for company logo and link back to home page */}
        <div >
          <Link to="/Home">
            <img src="./images/dnf - logo.png" alt="DNF - Logo" /> {/* logo */}
          </Link>
        </div>
        <div >
          <h6 >Get It Done Right,<br />The First Time.</h6> {/* Header slogan */}
        </div>
      </div>
    </header>
  );
}

export default NavBar;

If anyone knows the issue to this please help I don't know what, if anything, is wrong with my code.

CodePudding user response:

In your file where you import router, import BrowserRouter instead of just Router.

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

Also you have to use the <Link /> inside a <Router> component.

  <Router >
    <NavBar />  {/* the component which uses <Link /> */}
    <Routes>
      <Route exact path="/home" element={<Home />} />
    </Routes>
  </Router>

In my case it worked!

Just try to use the browser developer console to get more idea about the error.

CodePudding user response:

Wrap your Link tag and image with a Router tag.

<Router>
  <Link to="/Home">
    <img src="./images/dnf - logo.png" alt="DNF - Logo" /> {/* logo */}
  </Link>
</Router>

Don't forget to import

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