We have given an introduction to React-Table — a custom Hook to build an extendable table without the actual UI component. This type of component is called a headless UI component — it separates the logic and behavior of a component from its visual representation.

Headless UI components have a long journey with high order components, render props, and custom hooks. These concepts will be explained in this article.


High Order Components

We have a component that prints out a simple UI:

For this article, the source code is verified in [CodePen](https://codepen.io/):

const BaseComponent = (props) => <div>Value is {props.value} </div>;

	const App = () => <BaseComponent value={1} />;

	const rootElement = document.getElementById("root");
	ReactDOM.render(<App />, rootElement);

We want to make the text blue. This can be done by adding the style to line one or passing the style through line three. However, we want this style transformation logic to be reusable for other components too.

A high order component (HOC) is a good choice for this task. It’s a function that takes a component and returns a new component, with additional logic and behavior. It’s commonly defined as follows:

const EnhancedComponent = higherOrderComponent(WrappedComponent);

So, we create a HOC in the following code:

const withColor = (Comp) => (props) => {
	  const { color = "red", ...rest } = props;
	  return (
	    <div style={{ color }}>
	      <Comp {...rest} />
	    </div>
	  );
	};

	const BaseComponent = (props) => <div>Value is {props.value} </div>;

	const TransformedComponent = withColor(BaseComponent);

	const App = () => <TransformedComponent value={1} color="blue"/>;

	const rootElement = document.getElementById("root");
	ReactDOM.render(<App />, rootElement);

This HOC is named withColor (lines 1-8). It takes props and extracts out color if defined. Otherwise, it uses red as the default color (line 2). The rest props are passed down to the original component (line 5). It’s important to use composition, instead of mutating the original component.

#react #programming #javascript #nodejs #reactjs

A Journey With High Order Components, Render Props, and Custom Hooks
1.20 GEEK