Project Structure & Component Linking

Job ID: 39136213

Budget: $10 – $30 USD

We've already tackled building projects, and now we know the importance of deciding how to structure them. With this in mind, in this lesson, we'll take a look at how we can reuse and link the components in our project.

We'll keep the structure simple, so by the end of the lesson, it will look like this:
Importing components
The main feature of components is their reusability. You can also create components that are built of other components.

Suppose that we want the components Header and Main to appear in the root App component. Let's take a look at App.jsx and see how we can import them. This is as simple as importing modules, so this syntax might look familiar:
By using the import keyword, as we've already learned, we can easily import our components into other components.

The key thing to note above is that, to import Header and Main into App.jsx, we're referencing them using their relative file paths within our project.

On the other hand, to make these components accessible in other files, we rely on the export default statement. For example, our Header component will look like this:
The export default statement allows a component to be the main export from their respective files. This is crucial because when we import these components elsewhere in our project, we use their names directly.

Did you notice that we don't add a .jsx file extension for components when writing our import and export statements? Vite, when used with a React template, resolves the .jsx extension automatically. This is why you don't have to specify the extension while importing or exporting JavaScript files.
Let's put our new knowledge about project structure and importing components to real use in the Hello Vite! project. The last time we worked with it, we got rid of all the default Vite stuff. Now, let's start building our own components.

Create the components folder in src and create two new components inside: Header.jsx and Main.jsx.
Move App.jsx and App.css to the components folder.
Correct the path to App.jsx in the main.jsx file.
Move the JSX contents of App.jsx into Header.jsx:
Import both the Header and Main components into your root App component.
Add both to the JSX in your App.jsx component, <Header />, followed by <Main />. Don't forget that JSX can only have one outermost element, so you'll need to nest these inside a parent element or fragment!
Remove the <h1> and <p> tags from App.jsx since they are now in <Header> and <Main /> instead.
When you're done, your project should still look like this. Note that the favicon won't change until we replace it with the new one later.
Related categories: JavaScript CSS HTML React.js Server