Ala Ben Aicha
Ala Ben Aicha

Reputation: 1276

react cannot call a class as a function

I'm only using functional components in my project and despite that, I'm getting this error: Uncaught TypeError: Cannot call a class as a function.

This is part of the parent component where I get the error: (the problem is with the "withCheckCountry" component)

<Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/reset-password/:token" component={RestPass} />
        <Route path="/programs" component={About} />
        <Route path="/login" component={Login}>
          {loggedIn() && <Redirect to={redirectionPath()} />}
        </Route>
        <Route path="/signUp" component={SignUp}>
          {loggedIn() && <Redirect to={redirectionPath()} />}
        </Route>
        <Route
          path="/country/:countryCode"
          component={withCheckCountry(CountryApp, availableCountry, loadingCountry)}
        />

        <Redirect to="/" />
      </Switch>

and here is the "withCheckCountry" component:

import React, {useState, useEffect, memo} from 'react';
import PropTypes from 'prop-types';
import { Redirect } from 'react-router-dom';
import { toast } from 'react-toastify';
import ToastBody from "components/toastBody/toast";
import { FormattedMessage, injectIntl } from "react-intl";

const withCheckCountry = (Component, availableCountry, loadingCountry) => ({
  ...props
}) => {
  //console.log("props = "+JSON.stringify(props));
  if (!loadingCountry) {
    const { countryCode } = props.match.params;
    const isCountryExist = availableCountry.some(
      country => country.countryCode === countryCode.toLocaleUpperCase(),
    );
    const [errorTitle, setErrorTitle] = useState(intl.formatMessage(messages.errorTitle));
    const [countryNotExist, setCountryNotExist] = useState(intl.formatMessage(messages.countryNotExist));

    useEffect(() => {
      setErrorTitle(intl.formatMessage(messages.errorTitle));
      setCountryNotExist(intl.formatMessage(messages.countryNotExist));
    }, [intl]);

    if (!isCountryExist) {
      toast(() => <ToastBody title={errorTitle} message={countryNotExist} />);  
      return <Redirect to="/" />;
    }
  }
  return <Component {...props} />;
};

withCheckCountry.propTypes = {
  availableCountry: PropTypes.object,
};

export default injectIntl(withCheckCountry);

this error didn't show up until I added "injectIntl" when exporting the component, and I need that to get intl from props as you can see in the documentation here if you are interested.

Upvotes: 0

Views: 1969

Answers (1)

Chaymae
Chaymae

Reputation: 31

you are calling "withCheckCountry" component as if it was a function:
try this:

<Route path="/country/:countryCode" component={(props) => <withCheckCountry {...props} />} />

Upvotes: 1

Related Questions