Is it possible to match the # part of a route in React Router 4

前端 未结 3 1336
盖世英雄少女心
盖世英雄少女心 2021-02-20 04:04

In my app, I\'d like to match both the path and the hash to different components. For example:

/pageA#modalB

Would show PageA as the main page

相关标签:
3条回答
  • 2021-02-20 04:21

    if you actually want to match and get the parameters, use matchPath.

    import { useLocation, matchPath } from 'react-router-dom';
    
    // your route you want to see if it matches
    const routePath = '/overtherainbow/:country/#/city/:city/detail'
    
    // somewhere while rendering
    const location = useLocation();
    useEffect(() => {
      const matched = matchPath(location.pathname + location.hash, routePath);
      if (matched){
        // matched, do something with it, like setting state, fetching data or what not
        console.log(matched.params); // will be {country:..., city:...}
      }
    }, [location])

    0 讨论(0)
  • 2021-02-20 04:24

    @azium answer works fine as long as you don't need to use render or children prop in HashRoute. In which case this solution will work better :

    import React from 'react';
    import { Route } from 'react-router-dom';
    
    const HashRoute = ({ hash, ...routeProps }) => (
      <Route
        render={({ location }) => (
          (location.hash === hash) && <Route {...routeProps} />
        )}
      />
    );
    
    export default HashRoute;
    

    Use it like that :

    <HashRoute hash="#modalB" component={ModalB} />
    

    Or combine it with route matching :

    <HashRoute hash="#modalB" path="/subPageOnly" component={ModalB} />
    
    0 讨论(0)
  • 2021-02-20 04:29

    Not out of the box, but the beauty of React Router 4 is that it's incredibly easy to implement this yourself.

    let HashRoute = ({ component: Component, path, ...routeProps }) => (
      <Route 
        {...routeProps}
        component={({ location, ...props }) =>
          location.hash === path && <Component {...props} />
        }
      />
    )
    
    <HashRoute path="#modalB" component={ModalB} />
    
    0 讨论(0)
提交回复
热议问题