React’s Higher Order Components I use the most

1. Hidable — conditional rendering of a component

const HidableComponent = ({ isVisible, children }) =>
isVisible ? <>{children}</> : null;
const hidable = (Component) => {
const WithHidable = ({ isVisible, …rest }) => (
<HidableComponent isVisible={Component && isVisible}>
<Component {…rest} />
</HidableComponent>
);
return WithHidable;
};

2. Switcher — decides which component to render

const switcher = (selector) =>
React.forwardRef((props, ref) => {
const Component = selector(props);
return <Component ref={ref} {…props} />;
});
const mapStateToProps = (state: State) => ({
isMobile: isMobileView(state),
});
export default connect(mapStateToProps)(
switcher(({ isMobile }) => (isMobile ? MobileView : DesktopView))
);

3. withInitialize — helps with lifecycle props

class Initializer extends React.Component {
constructor() {
if (this.props.onConstruct) this.props.onConstruct();
}
componentDidMount() {
if (this.props.onDidMount) this.props.onDidMount();
}
componentWillUnmount() {
if (this.props.onWillUnmount) this.props.onWillUnmount();
}
render() {
return <>{this.props.children}</>;
}
}
const withInitialize = (Component) => {
const component = ({ onDidMount, onConstruct, onWillUnmount, ...rest }) => (
<Initializer
onDidMount={onDidMount}
onConstruct={onConstruct}
onWillUnmount={onWillUnmount}
>
<Component {...rest} />
</Initializer>
);
return component;
};

4. withPreventedOnClick — prevents the onClick event on a component

const withPreventedOnClick = (Component) => ({ onClick, ...rest }) => {
const handleClick = (e, ...args) => {
e.preventDefault();
onClick(...args);
};
return <Component {...rest} onClick={handleClick} />;
};

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React Experiments With Suspense for Data Fetching in Concurrent Mode

Regular Expressions(Regex) — JavaScript — Beginner to Expert

How Javascript Arrow functions make life easy

Building High-performance Apps: A Checklist To Get It Right

TypeScript infer Keyword

Entry Components

Creating Illusions in p5.js -Part 3 (Moving Dot Illusion)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mindaugas Nakrosis

Mindaugas Nakrosis

More from Medium

Brief introduction about ReactJS

Virtual DOM — the magic behind React

Starting Guide to useState() in React

React JS