简体   繁体   中英

Property 'props' does not exist on type '{}' (trying to get access to props of children) - React Typescript

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!

Use this generic with expected Props

FC<{ children: ReactElement<TabItemProps>[] }>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM