Home > Net >  How to add an additional argument to a function passed down as a prop in React?
How to add an additional argument to a function passed down as a prop in React?

Time:09-14

I've been wondering: When you create a function like the following:

const someFunction = (paramOne, paramTwo, paramThree) => {
    // some code 
}

And then pass it down to a component as a prop:

<SomeComponent somePropName={someFunction} />

And in said component, you call it with 2 arguments:

props.somePropName('value1', 'value2')

While the function's signature describes three arguments. Would there be any way to 'fill in' the third argument of said function in the main component, instead of the component where it's been passed down to:

<SomeComponent somePropName={someFunction(passedByComponent, passedByComponent, iWantToFillThisOneInManually)} />

The main reason I'd want this, is because sometimes I have data available in one file and other data in the other, while I do need both in the function.

Anyone have any experience doing something like this?

Thanks in advance!

Small note: Before shaking the brain bush, I'm not entirely sure if this is even possible :/

CodePudding user response:

Try this. paramThree will equal defaultValue by default. If you specifically enter a 3rd argument when you call the function, defaultValue will be ignored.

const someFunction = (paramOne, paramTwo, paramThree = defaultValue) => {
        // some code
}

CodePudding user response:

It can be done by creating a function with a single parameter that will encapsulate the original function (3 parameters) and set the first two parameters with some static value (const, state or whatever). Something like this:

const ComponentA = () => {
  const originalFunction = (paramA, paramB, paramC) => { ... }
  return <ComponentB myFunction={originalFunction} />
}

const ComponentB = ({ myFunction }) => {
  const derivedFunction = (param) => {
    myFunction('some value', 'other value', param)
  }
  return <button onClick={() => derivedFunction('test')}>try me</button>
}
  • Related