React tutorial using high order component in react typescript project
In this article i will explain you how you can use high order component in your react typescript project
Step 1: Create React typescript project
Create react typescript project or you can skip this step if you wanted to use high order component in to your existing project
npx create-react-app my-app --template typescript
Step 2: Create high order component in to your newly created or existing project
Create a file _ /src/hoc/hocComponent.tsx _ and copy paste the following code
import React, { ComponentType } from "react";
export interface AdditionalProps {
additionalProp: string;
}
export default function hoc<P extends AdditionalProps>(
WrappedComponent: ComponentType<P>
): ComponentType<Omit<P, "additionalProp">> {
const additionalProp = "sdfsd";
console.log("Inside hoc");
return (props) => (
<WrappedComponent additionalProp={additionalProp} {...(props as any)} />
);
}
Step 3: Use this high order component in other component
In this last and final step you need to wrap your component with this high order component which we have created
import React from "react";
import hocComponent from "../hoc/hocComponent";
const MyOtherComponent: React.FC<{}> = (props: any) => {
return <div>My other component</div>;
};
export default hocComponent(MyOtherComponent);