course content

Course Content

Introduction to React

Importing ComponentsImporting 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:

For example, consider the following component:

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:

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:

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.

question-icon

What is the syntax for exporting a component?

Select the correct answer

Everything was clear?

Section 4. Chapter 4