In React, importing and exporting components and variables are fundamental concepts that allow you to modularize your code. This section will explain different ways to import and export in React.
Each module can have one default export. This is useful for exporting a single primary value or component from a module.
// Greetings.jsx
const Morning = () => <h1>Good Morning!</h1>;
export default Morning;
You can also export multiple variables or components from a module using named exports. These are useful when you need to export multiple values from the same module.
// Greetings.jsx
const Morning = () => <h1>Good Morning!</h1>;
const Afternoon = () => <h1>Good Afternoon!</h1>;
const Evening = () => <h1>Good Evening!</h1>;
export { Morning, Afternoon, Evening };
You can combine default and named exports in the same module:
// Greetings.jsx
const Morning = () => <h1>Good Morning!</h1>;
const Afternoon = () => <h1>Good Afternoon!</h1>;
const Evening = () => <h1>Good Evening!</h1>;
export default Morning;
export { Morning, Afternoon, Evening };
Default exports are imported without curly brackets.
// App.jsx
import Morning from "./Greetings";
Named exports are imported using curly brackets.
// App.jsx
import { Morning, Afternoon, Evening } from "./Greetings";
You can import both default and named exports together.
// App.jsx
import Morning, { Afternoon, Evening } from "./Greetings";
You can import all exports from a module using the * as
syntax. This creates an object containing all the exports, which can be accessed as properties of that object.
// App.jsx
import * as greet from './Greetings';
<greet.default />
<greet.Morning />
<greet.Afternoon />
<greet.Evening />
By using the import and export functionality in React, you can organize and modularize your code, making it more maintainable and scalable.
Objective: Create three new components (Morning.jsx
, Afternoon.jsx
, Evening.jsx
) and export them. Then, import and use these components in App.jsx
.
Create Morning.jsx
:
import React from "react";
const Morning = () => {
return <h1>Good Morning!</h1>;
};
export default Morning;
Create Afternoon.jsx
:
import React from "react";
const Afternoon = () => {
return <h1>Good Afternoon!</h1>;
};
export default Afternoon;
Create Evening.jsx
:
import React from "react";
const Evening = () => {
return <h1>Good Evening!</h1>;
};
export default Evening;
Import and use these components in App.jsx
:
import React from "react";
import Morning from "./Morning";
import Afternoon from "./Afternoon";
import Evening from "./Evening";
const App = () => {
return (
<>
<Morning />
<Afternoon />
<Evening />
</>
);
};
export default App;
This task will help you practice creating, exporting, and importing components in a React application.