Search code examples
reactjstypescriptreact-propsazure-ad-msalhigher-order-components

How to pass props to HOC from calling component - React + Typescript


i created new PublicClientApplication in my index.tsx. Now I want to pass this to my withAuthHOC. This HOC is using by the App.tsx. So i want to use the PublicClientApplication (pca props) in HOC. How can I do it?

My AppProps.tsx:

export type AppProps = {
    pca: IPublicClientApplication
  };

My index.tsx:

const msalInstance = new PublicClientApplication(msalConfig);

ReactDOM.render(
  <React.StrictMode>
    <App pca={msalInstance} />
  </React.StrictMode>,
  document.getElementById('root')
);

My App.tsx:

  const App = ({pca}:AppProps) => {
  return (
      <MainRoutes />
  );
}

export default withAuthHOC(App);

My withAuthHOC.tsx:

const withAuthHOC = (WrappedComponent: React.FunctionComponent) => {
    return () => {
        useMsalRedirect();

        return (
            <MsalProvider instance={pca}>
                <AuthenticatedValidation />
                <AuthenticatedTemplate>
                    <WrappedComponent />
                </AuthenticatedTemplate>
            </MsalProvider>
        );
    }
};

export default withAuthHOC;

Solution

  • You will get it on props of the HOC

    const withAuthHOC = (WrappedComponent: React.FunctionComponent) => {
        return (props) => {
    
            const {pca} = props; // get pca form props
    
            useMsalRedirect();
    
            return (
                <MsalProvider instance={pca}>
                    <AuthenticatedValidation />
                    <AuthenticatedTemplate>
                        <WrappedComponent />
                    </AuthenticatedTemplate>
                </MsalProvider>
            );
        }
    };
    
    export default withAuthHOC;