I'm not sure if this is a TypeScript issue, or if it's more of a React props behavior question, or if it's simply me messing up ES6 destructuring.
I have a ParentComponent whose props are type ParentProps, and a ChildComponent which also has the same type. The ChildComponent consumes the same props, except for ONE prop which I now need to redefine (or if that's not possible, add a new one).
For this example let's say ParentProps is just buttonName: string and doSomething: (text: string) => void
I thought I could add to an object destructuring by spreading one object, then adding property: value after a comma, ie: {...props, additionalProp: doSomething} But that doesn't seem to work: Left side of comma operator is unused and has no side effects. Can anyone chime in on what my issue is here and what I'm doing wrong?
const ParentComponent: FC<ParentProps> = memo(function ParentComponent({
...props
}) {
function doSomething(text) {
console.log("did the thing", text)
}
return <ChildComponent {...props, doSomething: doSomething} /> // <----here's the problem
})
export function ChildComponent(props: ParentProps) {
return (
<button onClick={props.doSomething(props.buttonName)}>{props.buttonName}</button>
)
}
...or if it's simply me messing up ES6 destructuring.
return <ChildComponent {...props} doSomething={doSomething} /> // do this
You have to destructure an object (or array). You were confusing the JSX-property brackets with the brackets used to declare an object.
The example above will also overwrite a potentially existing property props.doSomething. React-props will overwrite previously defined props. However, it would be better if you were explicit about this change instead of implicitly overwriting it.