javascriptreactjsclassreact-hooksreact-class-based-component

how to import a function in react class component to using it multiple times?


for example i want to add a function to return or do something like this:

export const useExample = (name) => {
  const script = "hi" + " " + name;
  return script
};

and i want to use it in class component so should be this:

import React from 'React'
import {useExample} from "components/utils/useExample"

class App extends React.Component {

componentDidMount(){
  const hiMsg = useExample('John')
  console.log(hiMsg)
}
render(){
  return(
  <>
   <div>THIS IS AN EXAMPLE</div>
  </>
   )
}
}

This will give an error like this: React Hook "useExample" cannot be called in a class component. ...

I know that we cannot use hooks in class components, so what is the **fix **of this issue to make the use Example works?

I just want to know how I can import external files like functions who accept parameters and do something with it, and to use this file multiple times in React class component


Solution

  • Just don't have use at the beginning of your function name, so it doesn't think it's a hook function.

    Something like getGreeting instead of useExample.