I'm doing custom Tabs component and ran into some problems.
When I try to get access to the 'props' of children I get an error: Property 'props' does not exist on type '{}'
const Tabs: FC<{
children: ReactNode[];
}> = ({ children }) => {
const [activeTab, setActiveTab] = useState<TabLabel | null>(null);
useEffect(() => {
setActiveTab(children[0]?.props.label);
}, []);
}
I would not be surprised with this error if it appeared in another place where I am traversing the array of children using the map method.
{children.map(
(child) =>
isValidElement(child) && (
<button
className={cn('checkout-tabs_tab', { '-active': child.props.label === activeTab })}
key={child.props.label}
onClick={() => onSetActiveTab(child.props.label)}
role="tab"
type="button"
>
{child.props.label}
</button>
)
)}
The code above does not give an error when trying to access props. I know there is a check with isValidElement
react helper but if I do the same check in the place where I get the error, it gives me another one:
useEffect(() => {
if (isValidElement(children[0])) {
setActiveTab(children[0]?.props.label);
}
}, []);
// TS2571: Object is of type 'unknown'.
I'm kinda new to typescript/react and would be glad to have this behavior explained to me. Thank you!
CodePudding user response:
Use this generic with expected Props
FC<{ children: ReactElement<TabItemProps>[] }>