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

Time:01-23

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

CodePudding user response:

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.

CodePudding user response:

You can export only functions declared with the keyword function that way. If you use const export the functions at the bottom of your file like this:

export {useExample}

or if you have more methods in the same file, than:

export {useExample, someMoreFunctions}
  • Related