-1

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

3
  • Does useExample call any hooks (eg, useState, useEffect)? If it doesn't, then simply change the name so that it doesn't start with use, so the lint rule won't think it's a custom hook. Commented Jan 23, 2023 at 12:27
  • 2
    As the error already states, you are not supposed to use a hook in a class component. Hooks are for functional components. If you don't need to work with a hook in the first place, you can rename the method so it does not start with use. If you do need to work with a hook, you could create a HOC component that passes the hooks return value to the class component as a prop Commented Jan 23, 2023 at 12:28
  • You cannot use hooks in class components. The name of the function use... implies that's what it is. Change the name if it's not a hook. Commented Jan 23, 2023 at 12:31

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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}

3 Comments

Whilst this is correct, this doesn't address the main issue of the question
can you give me an example about this? (function keyword)
@underthewater - export function getGreeting() { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.