In React, you export multiple components using named export. In named export, you export like this:
export function ComponentName(){ //JSX code }
A file can have more than one named export.
import React from 'react'; export function ToDoList() { return ( <> <h1>ToDo List</h1> <ul> <li>Eat</li> <li>Sleep</li> <li>Repeat</li> </ul> </> ); } export function ShoppingList() { return ( <> <h1>Shopping List</h1> <ol> <li>Designer Jacket</li> <li>Floral Dress</li> </ol> </> ); }
You can also export the component after it has been declared. For this, you have to export it as an object.
import React from 'react'; function ToDoList() { return ( <> <h1>ToDo List</h1> <ul> <li>Eat</li> <li>Sleep</li> <li>Repeat</li> </ul> </> ); } function ShoppingList() { return ( <> <h1>Shopping List</h1> <ol> <li>Designer Jacket</li> <li>Floral Dress</li> </ol> </> ); } export { ToDoList, ShoppingList }
You import the exported component like this:
import { ComponentName } from './ComponentFile.js';
As you can see that you use curly braces to import the named exported components.
Here is how you would import ToDoList and ShoppingList into App.js file.
import React from 'react'; import { ToDoList, ShoppingList } from './Lists.js'; export default function App() { return ( <> <ToDoList /> <ShoppingList /> </> ); }
There is also an alternative way of exporting components in React.js, which is the default export. To default export a component, you have to use export default
.
Note: A file can have only one default exported component. Therefore, if you want to export more than one component in a file, export one of them as default export and the remaining as named export.
import React from 'react'; export default function ToDoList() { return ( <> <h1>ToDo List</h1> <ul> <li>Eat</li> <li>Sleep</li> <li>Repeat</li> </ul> </> ); } export function ShoppingList() { return ( <> <h1>Shopping List</h1> <ol> <li>Designer Jacket</li> <li>Floral Dress</li> </ol> </> ); }
Here is how you import the default exported component.
import ComponentName from './ComponentFile.js';
To import both default exported and named exported components, you do it like this:
import React from 'react'; import ToDoList, { ShoppingList } from './Lists.js'; export default function App() { return ( <> <ToDoList /> <ShoppingList /> </> ); }