Home > Enterprise >  How to create higher order function in react functional component
How to create higher order function in react functional component

Time:06-01

I am trying to create a HOC using react functional component that will take a component and some props, but I think I am missing something I did not get the props value in the component which I passed. I am also using typescript

My higher-order component:

interface EditChannelInfo {
  Component: any;
  setIsCollapsed: Function;
  isCollapsed: boolean;
}

const EditChannelInfo = (props: EditChannelInfo): ReactElement => {
  const {isCollapsed, setIsCollapsed, Component} = props;
  const {data: gamesList} = useGamesList();
  
  const games = gamesList.games.map((list: GamesList) => ({
    value: list.gameId,
    label: list.gameName,
  }));


  return <Component {...props} />;
};

export default EditChannelInfo;

From here I am passing the component to the higher-order component

import EditChannelInfoWrapper from '../EditChannelInfoWrapper';

const Dashboard: NextPage = (): ReactElement => {
  const [isCollapsed, setIsCollapsed] = useState<boolean>(false);

  return (
    <div>

      <EditChannelInfo
        Component={EditChannelInfoWrapper}
        setIsCollapsed={setIsCollapsed}
        isCollapsed={isCollapsed}
      />
    </div>
  );
};

export default Dashboard;

I am getting games undefined

interface EditChannelInfoWrapper {
  games: any;
}

const EditChannelInfoWrapper = (
  props: EditChannelInfoWrapper,
): ReactElement => {
  const {
    games,
  } = props;
  console.log(games);
  return ()
}

CodePudding user response:

It looks like you're not passing your games prop to the Component here: <Component {...props} />.

Add in your games prop and it should work as expected <Component {...props} games={games} />

  • Related