1

I am trying to do a basic router website like below. I want to add a "selected" class to elements when the "to" matches the current url path (so it can highlight the active link).

I don't see how to get the location into the App props so I can use the location to change the styling.

import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import "./App.scss";

function About() {
  return <h2>About</h2>;
}

function Projects() {
  return <h2>Projects</h2>;
}
function EmailList() {
  return <h2>EmailList</h2>;
}

function App(props) {
  console.log(props);
  return (
    <Router>
      <div id="router">
        <div id="nav">
          <Link id="about-link" className="" to="/">
            <div className="circle icon-about">
              <span>About</span>
            </div>
          </Link>
          <Link id="projects-link" className="selected" to="/projects/">
            <div className="circle icon-projects">
              <span>Projects</span>
            </div>
          </Link>
          <Link id="writing-link" to="/writing/">
            <div className="circle icon-writing">
              <span>Writing</span>
            </div>
          </Link>
          <Link id="mailing-list-link" to="/email-list/">
            <div className="circle icon-email-list">
              <span> Mailing List</span>
            </div>
          </Link>
        </div>
        <div id="content">
          <Route path="/" exact component={About} />
          <Route path="/projects/" component={Projects} />
          <Route path="/email-list/" component={EmailList} />
        </div>
      </div>
    </Router>
  );
}

export default App;
RobKohr
  • 6,611
  • 7
  • 48
  • 69
  • Possible duplicate of [React Router v4 - How to get current route?](https://stackoverflow.com/questions/42253277/react-router-v4-how-to-get-current-route) – Cjmarkham Mar 12 '19 at 17:17

2 Answers2

0

how about to check window.location.pathname inside App ?

0

You could use

<NavLink to="/" activeClassName="selected"> FAQs </NavLink>

instead of <Link>

https://reacttraining.com/react-router/web/api/NavLink

Khaladin
  • 418
  • 5
  • 11