Does react-router support relative links?

后端 未结 6 1245
不思量自难忘°
不思量自难忘° 2020-12-29 04:40

I\'m on this url:

/path1/path2

Then:


With this code the address in the

相关标签:
6条回答
  • 2020-12-29 05:12

    in react-router v4 relative paths are supported. The history library resolves relative paths 'just like a browser would' so that a

    <Link to="two" />
    

    or a

    history.push({ pathname: '..', search: 'foo=bar' });
    

    at the url site/path/one will redirect to site.com/path/two and site.com/three?foo=bar.

    However NavLink does not work with relative pathnames because it doesn't resolve it's own relative path (which is nontrivial to do). However there are some community packages for this, but I haven't tested them.

    Alternatively, and this is what I do, you can get a match object from your parent Route (or from the context router.route.match) and use it to build your relative to in NavLink:

    <NavLink to={`${match.url}/three`} />
    

    this way your component can work independent of it's parent Route(s).

    0 讨论(0)
  • 2020-12-29 05:12

    Actually react-router support relative links.

    Given URL like /clients/invoice/123 the behaviour is:

    https://github.com/ReactTraining/react-router/issues/5127

    0 讨论(0)
  • 2020-12-29 05:17

    As per the API documentation, links must be absolute:

    The to property of a Link must be a location descriptor, which is either a string (where it's explicitly stated that

    relative paths are not supported

    ), or an object with a pathname property, which is absolute (by its definition), too.

    There is an open issue discussing relative links, which seems to indicate that relative paths may be supported in future.

    Everything said here applies to react-router version 2.x and above.

    0 讨论(0)
  • 2020-12-29 05:20

    Also you can use this.props.match.url because the match object has the url Object which is the currently loaded path (the page you're currently on).

    In the end you can chain /path1/path2 and build a dynamic relative path like this this.props.match.url + /path1/path2

    Example:

    <Link to={{ pathname: this.props.match.url + /path1/path2 }}>Path name</Link>

    0 讨论(0)
  • 2020-12-29 05:23

    It is not supported, but you can easily generate an absolute path:

    <Link to={this.props.location.pathname + '/path3'}>
    
    0 讨论(0)
  • 2020-12-29 05:37

    Yes. Use the react-router-relative-links library. It was written by Ryan Florence, one of the original authors of react-router.

    To use your example, you'd want to use:

    { RelativeLink } = require 'react-router-relative-links'
    ...
    <RelativeLink to="./path3">My link text</RelativeLink>
    
    0 讨论(0)
提交回复
热议问题