Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass this TypeScript React component an optional prop?

I'm fairly new to TS and trying to understand how to pass optional props to this component that's a bit complex for me. I thought you could use a ? for the props that you want to be optional, but I'm getting the following error:

A binding pattern parameter cannot be optional in an implementation signature.

How would I pass optional props to this component?

With Optional Props

export const BGVideo = React.memo(function BGVideo({ src, children, bgColor? }: any) {
  return (                                                          ^^^^^^^^
    <BackgroundVideoContainer>...some other stuff...
  )
});

Original

export const BGVideo = React.memo(function BGVideo({ src, children }: any) {
  return (
    <BackgroundVideoContainer>...some other stuff...
  )
});
like image 508
ezeYaniv Avatar asked Sep 07 '25 05:09

ezeYaniv


1 Answers

What you're thinking of is declaring an optional property of a type. For instance:

interface Props { bgColor?: string }
const a: Props = { bgColor: '#fff' } // valid
const b: Props = {}                  // valid

But the only type in your code here is any, which is not a good practice to use as it disables all type checking.

So what you want to do is delcare the type for your props, which includes the optional property:

interface Props {
    src: string,
    children: React.ReactNode
    bgColor?: string
}

Then use that type.

export function BGVideo({ src, children, bgColor }: Props) {
  return (
    <>...</>
  )
}

Now in that function, bgColor has the type string | undefined. A string if it was passed a value, or undefined if it was not passed a value.

Working example


Lastly, React.memo really isn't necesary. You shouldn't really ever need to wrap a function component in this way. React.memo is more for values which you don't want to have to recompute.

like image 115
Alex Wayne Avatar answered Sep 09 '25 19:09

Alex Wayne