Reusable Components (Headers and Footers) in Next.js
Reusable components are used multiple times in a single project. Or we can also say that they are the general components like Header, Footer, Button, etc.
In this article, we see how to create reusable components in Next.js.
Let's create the app using:
npx create-next-app
The app will run at http://localhost:3000/.
Create a new file hello.js under the pages directory and update with the following content:
function HelloPage(){
return(
<div> Hello there, How are you? </div>
)
}
export default HelloPage
If you see, "Hello there, How are you?" on the browser, proceed further.
In the traditional world, a web app has Header, Footer and, buttons on every web page.
Let's create these components.
Under the root folder of the application, create another folder, components, And, under components create another folder 'common'.
Under the common directory, create two folders Header and Footer.
Under Header, create a file header.js and update the following:
function HeaderComponent() {
return (
<div>I am header component</div>
)
}
export default HeaderComponent
Under footer, create another file footer.js and update with the following content:
function FooterComponent() {
return (
<div>I am Footer Component</div>
)
}
export default FooterComponent
And then update the content of the hello.js with
import HeaderComponent from "../components/common/Header/header";
import FooterComponent from "../components/common/Footer/footer";
function HelloPage(){
return(
<div>
<HeaderComponent></HeaderComponent>
<br />
<div>
Hello there, How are you?
</div>
<br />
<FooterComponent></FooterComponent>
</div>
)
}
export default HelloPage
Visit the URL, http://localhost:3000/hello
By using this method, we can reuse the components in the Next.js.
AK Newsletter
Join the newsletter to receive the latest updates in your inbox.