how to read the properties of a react component passed to a regular function?

591 Views Asked by At

I have a HOC:

 function withNavigationWatcher(Component: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>) {
  console.log('withNavigationWatcher Component', Component.props)
  // eslint-disable-next-line react/display-name
  return function (props: any) {
    const { setNavigationData } = useNavigation();
    useEffect(() => {
      setNavigationData({ currentPath: props.match.path });
      // eslint-disable-next-line react/destructuring-assignment
    }, [props.match.path, setNavigationData]);

    return React.createElement(Component, props);
  };
}

it is called like a normal function, which is passed the component:

component: withNavigationWatcher(route.component),

So I can only access default props in withNavigationWatcher ? but is it possible to access the props property of component - even if they are not set, is there a reference to this property?

enter image description here

and the second question: taken in the second function? enter image description here

1

There are 1 best solutions below

1
Pranjal Koshti On

You need to pass both props, default props and component level props to returned component. Try to create new object with both props and sent it to component.

ley newProps = {...props, ...Component.props}

... return React.createElement(Component, newProps);

Please refer to this article

https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb I think instead on any you need to attach props interface

interface WithLoadingProps {
  loading: boolean;
}

const withLoading = <P extends object>(Component: React.ComponentType<P>) =>
  class WithLoading extends React.Component<P & WithLoadingProps> {
    render() {
      const { loading, ...props } = this.props;
      return loading ? <LoadingSpinner /> : <Component {...props as P} />;
    }
  };