I m using reactjs typescript for a react application.
I have a parent component called <Video>
, like so:
<Video
param1={param1}
param2={param2}
param3={param3}
/>
Inside Video component, there is a child component, the <VideoControls/>
<VideoControls
param1={param1}
param2={param2}
param3={param3}
/>
From page1
i call the <Video Param1={param1} Param2={param2} />
with just Param1 and Param2
, so i have a type :
type props {
param1: string,
param2: string,
param3?: string,
}
From page2
i call the <Video Param1={param1} Param2={param2} Param3={param3} />
with all the parameters.
But when it comes to the child component <VideoControls />
i dont know how to pass the parameters, because some times its all the 3 params and some times its just the 2 of them.
Should i pass all the 3 params and when it comes from page1
, the param3 will pass undefined ?
is there any doc for that case ?
CodePudding user response:
You should pass all of the props from the parent component to the child component, even if some of the props are optional. This will ensure that all of the props are available to the child component, and the child component can choose which props to use.
One way to do this is using the ...
spread operator. This will automatically include all of the props from the Video component, including any optional props that may not have been provided. For example:
const Video: React.FC<Props> = (props) => {
return (
<>
<VideoControls {...props} />
</>
);
}
Then, inside of VideoControls
, decide how you want to handle the props, depending on whether or not they are available.