I am using react-click-outside
to hide dropdown menus if the user clicks outside the menu. Normally, I would export the component like so:
export default enhanceWithClickOutside(Dropdown);
However, in this case, I want to export the component
export { enhancedWithClickOutside(Dropdown) };
But that apparently does not work. Is there a way to export using {}
and also apply the higher order component function?
In a modern React world, everyone uses function components with React Hooks. However, the concept of higher-order components (HOC) is still applicable in a modern React world, because they can be used for class components and function components.
We use higher order components to primarily reuse logic in React apps. However, they have to render some UI. Hence, HOCs are inconvenient when you want to share some non-visual logic. In such a case, React hooks seem to be a perfect mechanism for code reuse.
Higher-Order Components enable us to apply functional programming principles on components by embracing composition. React Hooks, in contrast, transformed pure (in the sense of functional programming) function components to stateful/side-effect burdened beasts. Anyway, both have their right to exist.
You can export as many functions as needed as long as you remember that there can be only one default export. The default export in JavaScript is used to export a single/fallback value from a module. With a default export, you do not need to specify a name for the exported function.
export class Dropdown extends React.component {
...
}
export const EnhancedDropdown = enhanceWithClickOutside(Dropdown);
Somewhere else
import { Dropdown, EnhancedDropdown } from 'path/to/Dropdown';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With