Home > Net >  How to extend a wrapped React.Component class?
How to extend a wrapped React.Component class?

Time:11-20

I have been following this answer to get redirection functionality added to a React project I have been working on.

I have a class that is currently extended by several other classes; this parent class currently extends React.Component:

class LoginForm extends Form {
   ...
}

export default LoginForm;
class Form extends React.Component {
   ...
   ...
}

export default withRouter(Form); 

This was working fine until I added this withRouter functionality on the component. I am now presented with the following error when the page loads:

Login.js:8 Uncaught TypeError: Class extends value props => {
    _s();
    const params = (0,react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useParams)();
    cons...<omitted>... } is not a constructor or null
    at ./src/pages/Forms/Auth/Login.js (Login.js:8:1)

The code for wrapping the class export is:

const withRouter = Wrapper => props => {
    const params = useParams();
    const navigate = useNavigate();
 
    return (
        <Wrapper
            {...props}
            navigate={navigate}
            params={params}
        />
    )
}

export default withRouter;

What do I need to do to be able to inherit this class? I do not want to refactor the whole site to use functional components, but we are using Router V6 - and I understand that using the hook is necessary. Is there a way to inject the property higher up to make this work?

CodePudding user response:

The only way to be able to extend something wrapped with a withSomething is for withSomething to return a class component.

Because of this, you won't be able to use any useSomething hooks in your withSomething function.

Without refactoring anything significantly, you should inherit from the base class and then use withRouter on your inherited class.

Alternatively, you could go back to React Router v5 and use their withRouter HOC

CodePudding user response:

It is deprecated. You can recreate it using the hooks version like this:

import {
  useLocation,
  useNavigate,
  useParams
} from "react-router-dom";

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return (
      <Component
        {...props}
        router={{ location, navigate, params }}
      />
    );
  }

  return ComponentWithRouterProp;
}

For more details, check here

  • Related