简体   繁体   中英

Conditional routing of components in react js

My code is as shown below. I want routing in such a way that if there is Appointment route active then login route link must be disappear. And if login component is routing then Appointment route link must be disappear. I got stucked. What condition should I enter here.


            <Link to="/" style={{height:'20px'}}><strong style={{fontSize:'15px' ,color:'#0'}}>Home</strong></Link>
            <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
            <Link to="/services" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Services</strong></Link>
            <Link to="/Login" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Login For Doctors</strong></Link>
            <Link to="/Appointment" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Todays Appointment</strong></Link>
        </Navigation>

There are a bunch of ways to conditional render components or jsx elements in react.

The Basic understanding you should grasp is: whenever you return false or falsey, it won't render.

There are a few techniques you could use, please refer to this article for more information

  1. if conditional
  2. ternary operator
  3. && operator (my personal favorite)
  4. Switch statement

You need to check useLocation() inside this file in order to know which path you are currently on, and then hide that path.

Here is a post which shows how to use useLocation(). Then you can use any method you want to hide that link. An example would be:

  {location !== '/contact'
      <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
       : null}

after setting location to the current path like this:

const location = useLocation().pathname

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