Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make withRouter HOC stateful to allow refs #5382

Closed
wants to merge 1 commit into from

Conversation

sanniassin
Copy link
Contributor

Right now when you use withRouter on a component with ref it suddenly breaks because withRouter is a stateless component which doesn't allow refs.

There is wrappedComponentRef property but it forces container to know which child components use withRouter and which don't.

Components refs are mostly used to get a DOM node via ReactDOM.findDOMNode so usually it doesn't matter if ref points to withRouter HOC instead of wrapped component.

@JustFly1984
Copy link

JustFly1984 commented Jul 28, 2017 via email

@JustFly1984
Copy link

JustFly1984 commented Jul 28, 2017 via email

@sanniassin
Copy link
Contributor Author

@JustFly1984 It affects both string and functional refs. Also findDOMNode isn't deprecated and useful for some edge cases or quick prototyping.

@timdorr
Copy link
Member

timdorr commented Jul 28, 2017

It was explained in #4838 that we do this because it follows the recommendation from the React docs. The ref you would get back from this component wouldn't be the correct one, as it points at the wrapper instead of the wrapped component.

@timdorr timdorr closed this Jul 28, 2017
@esellin
Copy link

esellin commented Oct 3, 2018

I ended up writing this utility function:

import {withRouter as withRouterOrig} from 'react-router-dom';

export function withRouter(Component) {
  Component = withRouterOrig(Component);
  return class WithRouterWrapper extends React.Component {
    render() {
      return (
        <Component
          wrappedComponentRef={ref => this.ref = ref}
          {...this.props} />
      );
    }
    getWrappedInstance = () => this.ref;
  };
};

Use like you would use the original withRouter(), but you can assign it a ref, and later call getWrappedInstance() on that ref, like you already do with other HOCs such as injectIntl(), connect(), etc.

I understand the future is forwardRef() (#6056), but until it is supported by react-redux
(see react-redux issue #914) and others, this will do me for now.

@lock lock bot locked as resolved and limited conversation to collaborators Dec 2, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants