I've got a Profile page that contains different sidebar options (UserInfo, MyCourse, Logout), and I want it so that when you select one of these options you get the corresponding component view. To do this, I created an object, componentToDisplay and chose the component based on the selected sidebar option. The problem is that the components receive different props, in this case Logout expects a handleCloseModal prop whereas UserInfo and MyCourses expect no props (yet).
type UserInfoProps = React.ComponentProps<typeof UserInfo>;
type MyCoursesProps = React.ComponentProps<typeof MyCourses>;
type LogoutProps = React.ComponentProps<typeof Logout>;
// Define prop types for each component
type UserInfoFunction = (props: UserInfoProps) => React.ReactNode;
type MyCoursesFunction = (props: MyCoursesProps) => React.ReactNode;
type LogoutFunction = (props: LogoutProps) => React.ReactNode;
// Create a new type that is a union of all component functions
type ComponentFunction = UserInfoFunction | MyCoursesFunction | LogoutFunction;
// Construct the componentToDisplay object
const componentToDisplay: Record<SidebarOptions[number], ComponentFunction> = {
Profile: (props: UserInfoProps) => <UserInfo {...props} />,
"My Courses": (props: MyCoursesProps) => <MyCourses {...props} />,
"Log Out": (props: LogoutProps) => <Logout {...props} />,
};
const Main = () => {
const [selectedSidebarOption, setSelectedSidebarOption] = useState<
SidebarOptions[number]
>(SIDEBAR_OPTIONS[0]);
const displayComponent = componentToDisplay[selectedSidebarOption];
const displayComponentProps =
selectedSidebarOption === "Log Out" ? { handleCloseModal } : {};
const component = displayComponent(displayComponentProps);
...
}
I'm getting an error here, what do I do
const component = displayComponent(displayComponentProps);
Argument of type '{ handleCloseModal: () => void; } | { handleCloseModal?: undefined; }' is not assignable to parameter of type 'Props'.
Type '{ handleCloseModal?: undefined; }' is not assignable to type 'Props'.
Types of property 'handleCloseModal' are incompatible.
Type 'undefined' is not assignable to type '() => void'.ts(2345)
const displayComponentProps: {
handleCloseModal: () => void;
} | {
handleCloseModal?: undefined;
}