3 • Build and design with Astro UI components
Make a reusable Navigation component
Now that you have the same HTML written in multiple pages of your Astro site, it’s time to replace that duplicated content with a reusable Astro component!
Get ready to…
- Create a new folder for components
- Build an Astro component to display your navigation links
- Replace existing HTML with a new, reusable navigation component
Create a new src/components/
folder
Section titled Create a new src/components/ folderTo hold .astro
files that will generate HTML but that will not become new pages on your website, you will need a new folder in your project:src/components/
.
Create a Navigation component
Section titled Create a Navigation component-
Create a new file:
src/components/Navigation.astro
. -
Copy your links to navigate between pages from the top of any page and paste them into your new file,
Navigation.astro
:
Import and use Navigation.astro
Section titled Import and use Navigation.astro-
Go back to
index.astro
and import your new component inside the code fence: -
Then below, replace the existing navigation HTML link elements with the new navigation component you just imported:
-
Check the preview in your browser and notice that it should look exactly the same… and that’s what you want!
Your site contains the same HTML as it did before. But now, those three lines of code are provided by your <Navigation />
component.
Try it yourself - Add navigation to the rest of your site
Section titled Try it yourself - Add navigation to the rest of your siteImport and use the <Navigation />
component in the other two pages on your site (about.astro
and blog.astro
) using the same method.
Don’t forget to
- Add an import statement at the top of the component script, inside the code fence.
- Replace the existing code with the navigation component.
Test your knowledge
Section titled Test your knowledge-
You can do this when you have elements repeated on multiple pages:
-
Astro components are:
-
Astro components will automatically create a new page on your site when you…
Checklist
Section titled ChecklistResources
Section titled Resources-
Refactoring external