1

Here is the structure of my folder:

 src--|

 |--ComponentsFolder1--Button.tsx

 |--ComponentsFolder2--ParentDiv.tsx
  

My problem is as follows: Button.tsx is a react component which calls a fetch function located in react ParentDiv.tsx with a few parameters:

type getNewVerseProps = {
   getNewVerseFunc: (event: React.MouseEvent<HTMLDivElement>) => string;
};

const Button = ({ getNewVerseFunc }: getNewVerseProps) => {
   return (
      <div>
               <div
                  onClick={getNewVerseFunc.bind(name, id)}>
               </div>
      </div>

Now, as you can see, I want to call the function on my ParentDiv.tsx file with the specified parameters in Button.tsx:

    const getNewVerseFunc = async (name: string, id: string) => {
      const requ = await fetch(
         `https://api.scripture.api.bible/${name}/${id}`,
         {
            method: "GET",
            headers: {
               "api-key": bibleApi,
            },
         }
   };

<Button getNewVerseFunc={getNewVerseFunc}/>

My problem is that the params in the function are not being passed down in the Button component when i call the getNewVerseFunc function in the ParentDiv component

1 Answer 1

4

First of all you've used bind wrongly. First argument is a context, which is in this case ignored, because you have an arrow function, which is instantly bound; but it is impossible to rebind bound function.

Common practice is to have button with onClick callback, like:

import { FunctionComponent } from 'react';

type Props = {
  onClick: MouseEventHandler;
}

const Button: FunctionComponent<Props> = ({ onClick, children }) => (
    <div onClick={onClick}>
        {children}
    </div>
);

And for simplicity avoid using bind, call or apply if possible; it's good that you are aware of these functions, but using them usually reduces readability.

Then in parent you can do the following:

import { FunctionComponent } from 'react';

const ParentDiv: FunctionComponent = () => {
    const name = 'Some name';
    const id = 'Some id';

    return (
        <Button onClick={() => getNewVerseFunc(name, id)}>
            Click me
        </Button>
    );
};

If your Button component is wrapped with memo, then it makes sense to use useCallback hook for onClick handler, but that's already micro optimisation.

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

3 Comments

Thank you very much for your response, it really helped! I appreciate it!
@D.R. You should consider accepting this answer to your question if it helped.
I think you forgot = in type Props = { onClick: MouseEventHandler; }

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.