2

I need to get the current path of the url on route change and based on the value I want to do conditional rendering

So here's my code and I don't have the idea to go forward.

import React, { useRef, useEffect, useState } from "react";
import "./App.css";
import "./css/custom.css";

import {
  BrowserRouter as Router,
  Switch,
  Route,
  useLocation,
} from "react-router-dom";

import NavigationBar from "./pages/homepage-components/1-navbar";
import HomePage from "./pages/HomePage";
import Post from "./pages/Post";

function NavigationHeader() {
  const location = useLocation();
  return location.pathname;
}

function App() {
  const [location, setLocation] = useState("");

  const mounted = useRef();
  useEffect(() => {
    if (!mounted.current) {
      // do componentDidMount logic
      let val = NavigationHeader; // this part return the function, even tried NavigationHeader(), but no luck
      alert(val);
      mounted.current = true;
    } else {
      // do componentDidUpdate logic
    }
  });

  return (
    <Router>
      {/* --------------- Navigation Bar --------------- */}
      {location === "/" ? <NavigationBar /> : null}
      

      {/* --------------- End of Navigation Bar --------------- */}
      <Switch>
        <Route exact path="/" component={() => <HomePage isroot={location} />} />
        <Route path="/post" component={Post} />
      </Switch>
    </Router>
  );
}

export default App;

So what I need to do is:

For every Route change I need to update the value for location and do the conditional rendering and pass that value (path) to the Homepage component too as a prop

Any idea, anyone?

Jananath Banuka
  • 2,951
  • 8
  • 57
  • 105

1 Answers1

2

You're redefining location:

const [location, setLocation] = useState("");
// ---^^^^^

Change that to something else.

And you don't need to define other function just for useLocation. You can use it like:

function App() {
  const location = useLocation()
  // ...
  useEffect(() => {
    console.log(location.pathname)
  }, [location])

Edit:

If even after this you got error, then probably your react-router version is not the latest or not that which have useLocation defined. Try followings:

  1. Remove react-router, react-router-dom from package.json

  2. Remove node_modules for cache clarity:

rm -rf node_modules/

  1. Retry installing them again:

npm install react-router react-router-dom

  1. Re-run the application:

npm start

Edit 2:

Checking this issue tells us that we can't use any hooks within the same component that puts BrowserRouter into the Tree.

Move your BrowserRouter out of that component. It can go in the ReactDOM.render()

So, you will need to define the BrowserRouter where you have render ie. index.js.

Check this post for more detail.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231