React Import & Export Component Pattern

Default export

// MyComponent.tsx
const MyComponent = () => <div>Hey, MyComponent</div>;
export default MyComponent;

// App.tsx
import MyComponent from './MyComponent';

Export

// MyComponent.tsx
export const MyComponent = () => <div>Hey, MyComponent</div>;

// App.tsx
import { MyComponent } from './MyComponent';

Rename import

// MyComponent.tsx
export const MyComponent = () => <div>Hey, MyComponent</div>;

// App.tsx
import { MyComponent as MySuperComponent } from './MyComponent';
export const App = () => <MySuperComponent />;

Group all imports and rename

// MyComponent.tsx
export const Switch = () => <div>Hey, Switch</div>;
export const Group = () => <div>Hey, Group</div>;

// App.tsx
import { * as MyComponent } from './MyComponent';
export const App = () => (
    <>
        <MyComponent.Switch />
        <MyComponent.Group />
    </>
);

Re-export all

// MyComponent.tsx
export const Switch = () => <div>Hey, Switch</div>;
export const Group = () => <div>Hey, Group</div>;

// MyParentComponent.tsx
export * from "./MyComponent";

// App.tsx
import { Switch, Group } from './MyParentComponent';
export const App = () => (
    <>
        <Switch />
        <Group />
    </>
);

Re-export, then group all imports and rename

// MyComponent.tsx
export const Switch = () => <div>Hey, Switch</div>;
export const Group = () => <div>Hey, Group</div>;

// MyParentComponent.tsx
export  * as MyComponent from "./MyComponent";

// App.tsx
import { MyComponent } from './MyParentComponent';
export const App = () => (
    <>
        <MyComponent.Switch />
        <MyComponent.Group />
    </>
);

Export type

// MyComponent.tsx
export type Gender = "Male" | "Female"; // Accept only "Male" or "Female"

// App.tsx
import { Gender } from './MyComponent'

Export interface

// MyComponent.tsx
export interface IUser {
    id: string;
    name: string;
}

// App.tsx
import { IUser } from './MyComponent'

Cross published at .NET Thailand

Acknowledgement: Thank you .net thailand team to review this article: dotnetthailand.github.io#84