Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export higher order components without 'export default'

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?

like image 275
davidhu Avatar asked Jun 01 '17 19:06

davidhu


People also ask

Do people still use higher-order components?

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.

Should you use higher-order 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.

Can we use higher-order components in functional component?

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.

Can you have more than one default export?

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.


1 Answers

export class Dropdown extends React.component {
  ...
}

export const EnhancedDropdown = enhanceWithClickOutside(Dropdown);

Somewhere else

import { Dropdown, EnhancedDropdown } from 'path/to/Dropdown';
like image 99
Andy_D Avatar answered Oct 11 '22 14:10

Andy_D