bhylu.com

Advertisements

React Higher-order Components

Read wrappers that return components without assuming they are the best choice for every reusable behaviour.

How it works

A higher-order component is a function that takes a component and returns another component. Older libraries often use this pattern to inject props or cross-cutting presentation. Composition and custom hooks are usually simpler for new small features. This example adds an explanatory frame without changing the wrapped component or hiding its inputs. The wrapper is created at module scope so it has a stable identity.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function withLocalNotice(View) {
  return function LocalView(props) {
    return (
      <section>
        <p>Local preview only</p>
        <View {...props} />
      </section>
    );
  };
}
function Item({ name }) {
  return <p>{name}</p>;
}
const PreviewItem = withLocalNotice(Item);
function App() {
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <PreviewItem name="Market basket" />
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

The wrapped item appears beneath a local-preview notice.

The wrapper forwards ordinary props and adds markup. This simple contract does not automatically forward refs, hoist static properties or solve display names. Those omissions matter in a real shared library. Avoid creating the wrapper inside App, which would create a new component type each render. When all you need is a visible frame, a component with children may be clearer.

For API contracts and version differences, use React’s official documentation.

Advertisements