Is empty string valid value for React Link?

旧街凉风 提交于 2021-02-10 18:44:06

问题


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.


回答1:


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.




回答2:


to is a required prop for Link. If the url is empty better to hide the whole component:

   {
      condition && (
        <Link to={"/some/other/url"}>
          <div>my content</div>
        </Link>
      );
    }

If for some weird reason you need to have empty url, you can pass a space:

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



回答3:


Use "javascript.void(0)" instead of using an empty string.

import {Link} from 'react-router';

mycontent

Kindly refer to docs What does "javascript:void(0)" mean?



来源:https://stackoverflow.com/questions/57586239/is-empty-string-valid-value-for-react-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!