Importing and Exporting React Component Reference
Default Import Export
Solution One
Components/Foo.js
const Foo = () => {return (<div>Foo</div>)}export default Foo
or
Components/Foo.js
function Foo(){return (<div>Foo</div>)}export default Foo
App.js
import Foo from './Components/Foo'
Solution Two
Components/Foo.js
export default Foo = () => {return (<div>Foo</div>)}
or
Components/Foo.js
export default function Foo(){return (<div>Foo</div>)}
App.js
import Foo from './Components/Foo'
Named Export
Single Component
Solution One
Components/Foo.js
const Foo = () => {return (<div>Foo</div>)}export { Foo }
or
Components/Foo.js
function Foo() {return (<div>Foo</div>)}export { Foo }
App.js
import {Foo} from './Components/Foo'
Option Two
Components/Foo.js
export const Foo = () => {return (<div>Foo</div>)}
or
Components/Foo.js
export function Foo(){return (<div>Foo</div>)}
App.js
import {Foo} from './Components/Foo'
Export/Import Multiple Components From Single File
Components/Elements.js
const Foo = () => {return (<div>Foo</div>)}const Bar = () => {return (<div>Bar</div>)}export { Foo, Bar }
or
Components/Elements.js
function Foo() {return (<div>Foo</div>)}function Bar() {return (<div>Foo</div>)}export { Foo, Bar }
App.js
import { Foo, Bar } from './Components/Elements'
Option Two
Components/Elements.js
export const Foo = () => {return (<div>Foo</div>)}export const Bar = () => {return (<div>Foo</div>)}
or
Components/Foo.js
export function Foo(){return (<div>Foo</div>)}export function Bar(){return (<div>Bar</div>)}
App.js
import { Foo, Bar } from './Components/Elements'
Keeping Apps Organized By Using A Component Staging File
Using a component staging file can make managment of apps with many components simpler.
Benefits of a component staging file
- If we refactor a components file name or path we only need to change the path name in a single file
- Reduces the number of import statements
Handling Default Exports in Staging File
Simple Example
Components/Atoms/Foo.js
export default Foo = () => {return (<div>Foo</div>)}
Components/index.js
export { default as Foo } from './Atoms/Foo'
App.js
import {Foo} from './Components'
Exmaple - One
Components/Atoms/Foo.js
export default Foo = () => {return (<div>Foo</div>)}
Components/Atoms/Bar.js
export default Bar = () => {return (<div>Bar</div>)}
Components/Atoms/Elements.js
export const ElemntOne = () => {return (<div>ElementOne</div>)}export const ElemntTwo = () => {return (<div>ElementOne</div>)}
Components/index.js
export { default as Foo } from './Atoms/Foo'export { ElemntOne, ElementTwo } from './Elements'
App.js
import {Foo,Bar,ElemntOne,ElementTwo} from './Components'