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

故事扮演 提交于 2019-12-04 08:38:50

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} />

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