1

I have two component that one passes some func as prop to another and I am not sure what is the proper way to do this without having to receive an eslint error:

Code:

<Parent> const doSmthHandler = useCallback((id: number)=> { //do some stuff },[]) <ComponentB> doSmth={()=>doSmthHandler(id)} // Here I get eslint warning: JSX props should not use arrow functions eslint warning </ComponentB> </Parent> 

Component B receives doSmth prop as function and has a button such as:

<Button onPress={doSmth}>Do stuff</Button> 

I wonder how do I pass some argument into the cuntion passed as cb prop into another component that I dont get eslint errors!

4
  • Have you tried the React hook useCallback? You can find documentation for it here Commented Feb 10, 2021 at 15:37
  • I actually have it already under callBack() but the warning still shows! Commented Feb 10, 2021 at 15:39
  • dont see any example from above link how do you pass arg to the func without having to use inline arrow fn Commented Feb 10, 2021 at 15:46
  • @isnihalsi the problem is that you're passing a callback directly as a property. You should declare it before passing it down to the component to avoid the ESLint warning. Commented Feb 10, 2021 at 15:48

1 Answer 1

2

The problem with your code is that you're passing a callback as a property directly. You could declare it as a wrapper using useCallback before passing it down to the component, like so:

const doSmthHandlerWrapper = useCallback( () => doSmthHandler(id), [id] ) <ComponentB> doSmth={doSmthHandlerWrapper} </ComponentB> 
Sign up to request clarification or add additional context in comments.

9 Comments

how do you pass id inside doSmthHandlerWrapper?
Have you declared id on your component (Parent in your example code)? If so, it should be visible to the function via closure when the it's called.
no, actually this is the key point here, I would like to pass an arg to doSmthHandlerWrapper() for ex doSmthHandlerWrapper(1)
Can you provide a snippet with a broader version of your code, showing what you're tring to do?
it seems like I can simply do like <ComponentB doSmth={doSmthHandler(id)}/>
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.