profile
viewpoint

Ask questionsUse new forwardRef API in withRouter HOC

React 16.3 is out and now we have an "official" way to pass ref through HOCs with new forwardRef API. Would you like to use it as a replacement for wrappedComponentRef prop to make wrapping transparent for parent components?

Can submit a PR.

ReactTraining/react-router

Answer questions pandaiolo

As suggested in original SO question, here is a version built on @ranjith-s work, a bit simpler and that supports displayName which can be useful in tests or dev tools.

const withRouterAndRef = Wrapped => {
  const WithRouter = withRouter(({ forwardRef, ...otherProps }) => (
    <Wrapped ref={forwardRef} {...otherProps} />
  ))
  const WithRouterAndRef = React.forwardRef((props, ref) => (
    <WithRouter {...props} forwardRef={ref} />
  ))
  const name = Wrapped.displayName || Wrapped.name
  WithRouterAndRef.displayName = `withRouterAndRef(${name})`
  return WithRouterAndRef
}
useful!

Related questions

Route is not exported in react-router-dom
Cannot read property &#39;location&#39; of undefined at useLocation hot 4
Error: Invariant failed: You should not use <Switch> outside a <Router> hot 3
Replace componentWillMount by UNSAFE_componentWillMount for v3 hot 3
Failed prop type: Invalid prop 'component' supplied to 'Route': the prop is not a valid React component hot 2
useParams and other new hooks are not exported in react-router-dom & react-router hot 2
Prompt in React 16 "Warning: A history supports only one prompt at a time" hot 1
Fix <Route children> hot 1
Route is not exported in react-router-dom hot 1
bug: react router dom 4.3.1 pulling react-router 4.4.0 changes after latest publish hot 1
[React.memo] Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function` hot 1
Receiving ESM Error but not using ESM hot 1
useParams returns empty object when used outside of Route hot 1
useParams and other new hooks are not exported in react-router-dom & react-router hot 1
Add useRouter Hook - react-router hot 1
Github User Rank List