logo
Back to blogs

Higher Order Components in React (HOC)

Mar 10, 2023 - 5 min read

Higher Order Components in React (HOC)

Example of a Higher Order Component:

with-logging.tsx
1import React from "react"; 2 3const Label = ({ name, color }: { name: string, color: string }) => { 4 return ( 5 <div> 6 <p style={{ color: color }}>Hello {name}</p> 7 </div> 8 ); 9}; 10const withHey = (Component: React.FC, label: string) => { 11 return (props: any) => { 12 const newProps = { [label]: "Hey" + props[label] }; 13 return <Component {...newProps} {...props} />; 14 }; 15}; 16const SayHey = withData(Label, { label: "name" }); 17 18export const DemoHOC = () => { 19 return <RedTitle size="20px" />; 20};

In this example, we have a higher-order component that takes a component and a label as arguments. The higher-order component returns a new component that adds "Hey" to the value of the label prop. We then use the higher-order component to create a new component called SayHey that adds "Hey" to the value of the name prop.