Importing Components
Writing all the components in a single file is not a very good idea since it can become problematic and hard to manage as the code grows.
To avoid that, we divide the code into smaller parts (also called modules). React allows us to import components from other files using the import statement:
import ComponentName from RelativeFile
For example, consider the following component:
import React from "react";import ReactDOM from "react-dom/client";function ExampleComponent(props) {return (<div><h1>Heading</h1><p>This is an example of a component imported from another file.</p></div>);}const root = ReactDOM.createRoot(document.getElementById("root"));root.render(<ExampleComponent />);
This is a small script, but it is sufficient to show how we can divide a script into smaller parts.
We will create a new file called example.js and put the following code inside.
Export default function:
export default function ExampleComponent() {return (<div><h1>Heading</h1><p>This is an example of a component imported from another file.</p></div>);}
Notice how there's an export default
before the function. This is the syntax for exporting a function or component so it can be used in another file. We will save this file in the same directory as index.js. Finally, we will make the following modifications to the index.js file:
import React from "react";import ReactDOM from "react-dom/client";import ExampleComponent from "./example";const root = ReactDOM.createRoot(document.getElementById("root"));root.render(<ExampleComponent />);
We imported the ExampleComponent
using the syntax import ComponentName from ComponetPath;
and removed the component code from this file.
That is it! We have successfully imported a component. You can check the result in the browser, there should be no changes in the appearance or functionality of the website.
¡Gracias por tus comentarios!