0

This questions may already exist, if so link off to it and I can close this. Could not find an answer or proper phrasing.

I want to pass a value to the function that will be sent into my component. For example, I want to do the same as what an event handler does. Except that I want to be passing the value (ie the event obj or in my case and id).

const Foo = ({ onSort }) => {
    return <Bar onSort={ onSort } />;

Lets say the contract for onSort is (a: Array<T>, b: Array<T>, id?: string). I am not sure that this how the function contract should be but I want to be the one passing the id into the onSort that is given as prop to Bar. Hope that makes sense.

Do I just wrap it and send it in? But that would just call it no?

Pedro Mutter
  • 1,178
  • 1
  • 13
  • 18
MattyP
  • 25
  • 11

2 Answers2

0

If I understand you well, you want to send a function to a child component, right? As I can see you are using Typescript, so you will need to create the interface of the component props to create its signature.

interface BarProps {
 onSort: (id: string) => void
}

class Bar extends React.Component<BarProps> {}

Then, to use your component you will need to provide to Bar a function to onSort that respects the interface.

const Foo = ({ onSort }: {onSort: (param: string) => void}) => {
    return <Bar onSort={(id: string) => onSort(id) } />;
}

If Foo's onSort property has the same signature as Bar's onSort, then you can pass it directly.

Ps: The id parameter value, in this case, must always come from Bar component.

Pedro Mutter
  • 1,178
  • 1
  • 13
  • 18
0

We can use bind or arrow function to pass value to function prop as described here: https://stackoverflow.com/a/39226976/7245915

But a good way to pass value to a function prop is: https://stackoverflow.com/a/49337689/7245915