简体   繁体   中英

How to return jsx based on which path the user is on

(Please note that I'm a complete beginner. Thank you for your patience.) I have a navigation in my react app where I have 3 links, but once the user goes to another site, like for instance /about I would like the navigation bar to return a different link instead of a previous one, so instead of a chat icon going to /chat to the right of the navigation, it should change to an account icon that goes to /about).

I was thinking that I could do a if/else statement in the navigation component for each path. Ie: if (path == /about) { return (.... ) }

if (path == /home) { return (.... ) }

if (path == /checkout) { return (.... ) }

But I haven't managed to store which path the user is currently on.

I've tried to google and try different things out, but none unfortunately work for me. Am I even thinking of the right solution to this feature? If this is a matter of using hooks vs redux then I'd like to use hooks..

Thank you very much in advance!

Assuming that you're using React Router, you can import useLocation from 'react-router-dom`:

import { useLocation } from 'react-router-dom'

The useLocation hook provides information about the current URL, including pathname , which is the variable you want to switch on:

// inside component:
const { pathname } = useLocation()

switch(pathname) {
  case '/checkout': {
    // return ...
  }
  case '/about': {
    // return ...
  }
  case '/home':
  default: {
    // return ...
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM