javascriptreactjshigher-order-components

React: Include new prop to the Child Component in Higher Order Component


This is the Higher-Order Component class

token is the prop which I want to include

   import React from "react";
    
    export function requireAuthentication(Component) {
        return class AuthenticatedComponent extends React.Component {
    

            isAuthenticated() {
                return this.props.isAuthenticated;
            }

            render() {;
    
                return (
                    <div>
                        { this.isAuthenticated === true ? <Component token={token} {...this.props} /> }
                    </div>
                );
            }
        };
    }
    
    export default requireAuthentication;

When I access the props of the Component, I get props.token as undefined? Is there any way to pass new props?


Solution

  • I guess you need to get the token to the component if the component has another prop called isAuthenticated. You can do it like below.

    import React from "react";
    
    export function requireAuthentication(Component) {
      return class AuthenticatedComponent extends React.Component {
        isAuthenticated() {
          return this.props.isAuthenticated;
        }
    
        render() {
          return (
            <div>
              {this.props.isAuthenticated === true ? (
                <Component
                  token={"this_token_is_retrieved_by_requireAuthentication"}
                  {...this.props}
                />
              ) : (
                <Component {...this.props} />
              )}
            </div>
          );
        }
      };
    }
    
    const MyComp = requireAuthentication(({ token }) => {
      return <div>token: {token}</div>;
    });
    
    export default function App() {
      return (
        <div className="App">
          <MyComp isAuthenticated={true} />
          <MyComp isAuthenticated={false} />
        </div>
      );
    }
    

    Code sandbox