Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is empty string valid value for React Link?

I'm writing a React.js application where I want to use Link component from react-router package in order to conditionally redirect a user to another page. If some condition doesn't hold I set the to prop to empty string which works and doesn't cause page reload and the page stays in the exact same place it was. But I'm wondering if this is the best practice?

This is my solution:

import { Link } from 'react-router';

<Link to={condition === true ? '/some/other/url' : ''}>
    <div>
        my content
    </div>
</Link>

I don't see anything in the documentation regarding empty string input.

like image 602
hitchhiker Avatar asked Oct 23 '25 14:10

hitchhiker


1 Answers

I've never linked something to nothing in HTML or React. That said, it seems you have few options:

Option 1 Conditionally render the div not the to attribute. If codition is true show Link with div if not show div with no Link. This is probably the more "common" way to do this. If your div is not as simple as 'My Content' I would move it into a functional Component. And use that component instead of <div>MyContent</div> shown below.

import { Link } from 'react-router';

{ condition ? 
   (
     <Link to='/some/other/url'>
      <div>My Content</div>
     </Link>
   ) : ( <div>My Content</div> )
} 

Option 2 Do what you did but use the # instead of an empty string.

import { Link } from 'react-router';

<Link to={condition === true ? '/some/other/url' : '#'}>
    <div>
        my content
    </div>
</Link>

Option 3 Disable the link if the condition is false.

import { Link } from 'react-router';

//a better name might be in order here
const handleLinkDisable = (e) => {
  const { condition }  = this.state; //just assuming it comes from state
  if(condition){ e.preventDefault(); }
}; 

<Link to='/some/other/url' onClick={handleLinkDisable}>
  <div>My Content</div>
</Link> 

Hope that helps.

like image 140
Bens Steves Avatar answered Oct 25 '25 04:10

Bens Steves