React call from class to functional component. Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Viewed 1341

I am calling a functional component from a class component. This is my functional component,

import React, { useState, useEffect } from "react";
import {useNavigate} from "react-router";

const UtilsExt = () => {
    const navigate = useNavigate();
    navigate('/');

};

export default UtilsExt;

I am calling above from a button click event from a class component. When i do that i get this error.

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
1 Answers

React hooks can only be called in function components or custom React hooks. In order to use the navigate function you'll need to either create a wrapper component or a custom withNavigate HOC to pass navigate as a prop to your class component.

Wrapper

const MyComponentWithNavigation = props => {
  const navigate = useNavigate();

  return <MyClassComponent {...props} navigate={navigate} />;
};

Usage:

<Route path="..." element={<MyComponentWithNavigation />} />

HOC

const withNavigate = Component => props => {
  const navigate = useNavigate();

  return <Component {...props} navigate={navigate} />;
};

Usage:

const MyComponentWithNavigation = withNavigation(MyClassComponent);

...

<Route path="..." element={<MyComponentWithNavigation />} />

Accessing the navigate function

In your class component, access navigate from props.

this.props.navigate("/");
Related