Modify function's return value that's passed in as prop to a component

Viewed 42

Given I have a component that accepts a function as a prop (i.e. (item) => ({ value: item }) I want to modify that functions return value inside the component that's accepting it. Essentially, I want to wrap the function's return value in a JSX element. Like so:

const callback = ({ foo, bar }) => ({
  prop1: foo,
  prop2: bar
})

const MyComponent = ({ callback }) => {
  const someItems = [{name: 'one', foo: 1, bar: 1}, {name: 'two', foo: 2, bar: 2}]
  // modify callback in here to instead return <InternalComponent prop1={foo} prop2={bar} />
  // i.e. I want to pass the function's return value to InternalComponent as props
  // const callback = ({ foo, bar }) => {
  //   return <InternalComponent
  //     prop1={foo}
  //     prop2={bar}
  //   />
  // }
  return someItems.map(callback)
}

Is this possible?

1 Answers

If I understand your problem correctly, you can create a new function inside the MyComponent to spread the object that comes from callback on the InternalComponent and pass that new function to your someItems.map:

const MyComponent = ({ callback }) => {
  const someItems = [{name: 'one', foo: 1, bar: 1}, {name: 'two', foo: 2, bar: 2}];

  const newCallback = (someItem) => {
    const props = callback(someItem);
    
    return <InternalComponent ...props />
  }
  
  return someItems.map(newCallback);
}
Related