Hey there, fellow React enthusiasts! 👋 Are you loving React but sometimes find yourself tangled in the web of server-side rendering and SEO? Yeah, me too. This is how I came across Next.js, let me tell you why I think it's a game-changer for React developers and web developers in general.
Picture this: Next.js is like that cool cousin who knows all the shortcuts around town and the new trends of the time. Built on top of React, it gives you all the awesome features you're familiar with and then adds a sprinkle of magic. We're talking server-side rendering, static site generation, refined routing structures from the /pages and /app routing methods and even automatic code splitting right out of the box.
But wait, there's more! Ever wondered what kind of projects you can whip up with Next.js? Well, the sky's the limit. From snazzy blogs and portfolios to heavy-duty e-commerce platforms—you name it, you can build it. And if you're wondering about straying away from industry standard React.js, big names like Netflix and Uber are already riding the Next.js wave.
By the end of this article series, you'll have a deeper understanding of Next.js and how to leverage its features to build better React applications. Whether you're a beginner looking to start a new project or an experienced developer aiming to optimize an existing React application, Next.js has something to offer.
So, why should you stick around for this article series? By the end, you'll not only understand the what and the why of Next.js, but you'll also get hands-on experience with the how. Whether you're just dipping your toes into React or you're an old-timer looking to up your game, there's something in here for everyone.
Grab a cup of coffee (or tea, if that's your jam) and let's dive in!
2. Getting Started with Next.js
Installing Next.js
First things first, you'll need to install Next.js on your computer. Open your terminal, choose an empty file and run the following command to create a new Next.js project:
npx create-next-app my-nextjs-app
This command uses npx
to run the create-next-app
package and sets up a new Next.js project in a folder called my-nextjs-app
. Navigate into your new project folder:
cd my-nextjs-app
Understanding the Directory Structure
Alright, so you've successfully set up your Next.js project. High five! 🙌 Now, when you peek inside your project folder, you'll see a few directories and files. Let's break them down, shall we?
pages/: Think of this as the heart of your Next.js app. Every React component you place here turns into its very own webpage. Yep, it's that simple!
public/: Got some images or maybe a cool favicon? Drop all your static files right here.
styles/: This is your fashion closet for the website. Global styles, CSS modules—you name it, they all hang out here.
package.json: This is like your project's ID card. It keeps track of all the libraries you're using, along with some handy scripts.
next.config.js: This one's optional. It's like the settings menu in a video game—you don't have to mess with it, but it's there if you want to tweak how your Next.js app behaves.
Creating a Custom _app.js
Okay, let's get a bit fancy. Ever wanted to share some layout or styling across all your pages? That's what _app.js
is for. It's like the overcoat you wear on top of all your outfits.
Go ahead and create a new file in the pages
folder, and let's call it _app.js
. Then, copy-paste the code below. This is your basic setup, and it's going to help you add those shared styles or layout elements across your app.
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
This is a basic _app.js
setup. Any global CSS imports should be placed at the top of this file. The Component
and pageProps
props are automatically provided by Next.js, and they respectively represent the active page and its props.
Running the Development Server
To see your Next.js app in action, run the development server with the following command:
npm run dev
Open your web browser and navigate to http://localhost:3000
. You should see the Next.js starter page.
3. Basic Routing in Next.js
The Simplicity of Routing in Next.js
Okay, let's talk routing. If you've dabbled in React before, you might have had to wrestle with a library like React Router. But guess what? Next.js comes with its own built-in GPS—its routing system—and it's so easy, it feels like cheating. Seriously, it's like getting the VIP pass at an amusement park. 🎢
Creating New Pages
So, how do you create a new page or route? Easy! All you've got to do is drop a React component into the pages
folder. Want an "About" page? Create an about.js
file in the pages
folder and bam! You've got yourself a shiny new /about
route. This represents a different way of routing than what we have learned in React.js
For example, let's say you want a super-basic "About" page. Just like this:
// pages/about.js
function About() {
return (
<div>
<h1>About Us</h1>
<p>This is the about page.</p>
</div>
);
}
export default About;
After saving this file, you can visit http://localhost:3000/about
to see your new About page. No need to update any router configuration!
Dynamic Routing:
Next.js also supports dynamic routes. For example, if you want to create a page that displays details for a product with a specific ID, you can create a file like [id].js
inside a products
folder within pages
.
// pages/products/[id].js
function Product({ id }) {
return (
<div>
<h1>Product {id}</h1>
<p>This is the product page for product {id}.</p>
</div>
);
}
// Fetch the ID from the route parameters
export async function getServerSideProps(context) {
const { id } = context.query;
return { props: { id } };
}
export default Product;
How _app.js
Affects Routing:
The _app.js
file you created earlier acts as a wrapper around all your pages. This means you can use it to add functionalities that are common across all routes, such as navigation menus or footers.
For instance, you could modify _app.js
like this:
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return (
<div>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
<Component {...pageProps} />
</div>
);
}
export default MyApp;
Now, the navigation menu will appear on all your pages.
4. Linking Between Pages
The Importance of Client-Side Navigation
So, you know those times when you click a link on a website and it feels like you're waiting a century for the new page to load? Yeah, that's what happens when you're dealing with old-school, full-page reloads. Not cool, right? 😓
But here comes Next.js to the rescue with its sleek client-side navigation. It's like upgrading from a bicycle to a sports car. 🏎️ Only the parts of the page that need to change actually change, making the whole experience smoother for the you, the developer, and the overall the user.
Using the Link Component
Now, let's get into the nitty-gritty. How do we make this happen? 🔗
Meet Next.js's Link
component. It's your magic carpet for zipping between pages without that annoying page reload.
Ready to take it for a spin? First off, you'll need to invite the Link
component to the party by importing it from the next/link
package.
import Link from 'next/link';
Then, wrap the Link
component around the content you want to turn into a clickable link. For example, to link to the About page you created earlier:
<Link href="/about">
<a>About Us</a>
</Link>
The href
attribute specifies the path to the page you want to navigate to.
Linking with Dynamic Routes
If you have dynamic routes, you can also pass data using the Link
component. Suppose you have a product page that uses the route /products/[id]
. You can link to it like this:
<Link href={`/products/${productId}`}>
<a>View Product</a>
</Link>
Here, productId
would be a variable containing the ID of the product you want to display.
Prefetching with Link
One of the powerful features of Next.js's Link
component is automatic prefetching. When a Link
component appears in the viewport, Next.js automatically prefetches the linked page, making the navigation feel instant. You don't have to do anything extra to enable this; it's a built-in optimization!
Integrating Link
with _app.js
Since _app.js
acts as a global wrapper, you can include global navigation links there. You've already seen a simple example of this in the previous section. You can expand that by adding more Link
components to your navigation bar:
import Link from 'next/link';
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return (
<div>
<nav>
<Link href="/"><a>Home</a></Link>
<Link href="/about"><a>About</a></Link>
</nav>
<Component {...pageProps} />
</div>
);
}
export default MyApp;
5. Conclusion
Hey, give yourself a pat on the back! 🎉 You've just taken your first steps into the incredible world of Next.js. So what have we unpacked together in this intro article?
First off, we chatted about why Next.js is like the superhero React never knew it needed. It swoops in to save the day when you're grappling with tricky stuff like server-side rendering and making your site more Google-friendly. 🦸♀️🦸♂️
Then, we rolled up our sleeves and dove head-first into setting up a Next.js project. You got a backstage pass to the directory structure and even learned how to create a custom _app.js
file. That's like your personal magic wand for global settings!
And let's not forget our adventure into routing! With Next.js, creating new pages and jumping between them is as easy as pie. No magic spells required, just a simple Link
component. 🍰
But hey, we're just warming up here! There's a whole universe of Next.js goodies waiting to be explored. In our upcoming articles, we'll venture into the deep waters of data fetching, API routes, and how to make your site look snazzy.
So whether you're a React newbie eager to dive deeper or a seasoned pro looking for some new tricks, stick around. Next.js has a treasure trove of features that'll make your developer life a whole lot easier. Can't wait to see you in the next article! 💻✌️