Search code examples
reactjsreact-routercomponentsreact-router-dom

How can I use react-router-dom to navigate to another route within my web page?


I'm learning to use React and I'm stuck with a problem. I would appreciate it if you could help me. In a component, I have inserted a link, and I want it so that when clicked, it takes the user to a completely new page (within my own site) to display, but I haven't been able to achieve it.

Reading and watching videos, I've seen that it's done using "react-router-dom". I've managed to make it work partially, but it inserts the component information into my main page, and what I'm looking for is to be able to visit that new route or component on a new page of my site. In other words, I don't know how to render the linked component. Thanks!

///Component where the link I want to redirect to is located

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

function Skills() {
    return(
        <div id = "bioContainer">
            <h2>My Skills</h2>
                <div id = "bioText">
                    <ul className="skills-list">
                        <li className="frontend">HTML</li>
                        <li className="frontend">CSS</li>
                        <li className="frontend">React</li>
                        <li>Javascript</li>
                        <li className="backend">Node.js</li>
                        <li>Github</li>
                        <li className="backend">PostgreSQL</li>
                        <li>Python</li>
                    </ul>
                    <h2>"xxx</h2>
                    <h3>Who am I?</h3>
                    <p className="about">xxx</p>
                    <Link to="/Bio">See more</Link>
                </div>
        </div> 
    );
}

export default Skills;

/// App component

import React from "react";
import Header from "./Header";
import Skills from "./Skills";
import Projects from "./Projects";
import Footer from "./Footer";
import Get_in_touch from "./Get_in_touch";
import Bio from "./Bio";
import {Route, Routes} from "react-router-dom";

function App() {
  return (
      <div className="App">
          <Header />
          <Skills />
          <Routes>
            <Route path="/bio" element={<Bio />} />
          </Routes>
          <Projects />
          <Get_in_touch />
          <Footer />
      </div>
  );
}

export default App;

Solution

  • If you would like for Skills to be rendered on a separate page from Bio then create a separate route for it.

    Example:

    function App() {
      return (
        <div className="App">
          <Header />
          <Routes>
            <Route path="/" element={<Skills />} />
            <Route path="/bio" element={<Bio />} />
          </Routes>
          <Projects />
          <Get_in_touch />
          <Footer />
        </div>
      );
    }
    

    You can do the same for Projects and Get_in_touch as well if you like so they are not also rendered on each "page".