Cogito Ergo Sum
Cogito Ergo Sum

Reputation: 810

NextJS: How to parameterize function to render specific content based off link?

I have the following in /pages/index.js:

export default function Home() {
  return (
    <div className={styles.grid_container}>
      <NavBar/> 
      <div className={styles.center_pane}>
        <Overview/>
      </div>
      <div className={styles.right_pane}>
        <h2>Right Pane</h2>
      </div>
      <Footer/>
    </div> 
  )
}

It renders everything fine but I need some way of parameterizing the <Overview/> element so that depending on what page the user navigates to from the <Navbar> it will render the corresponding component.

The option I was considering was just creating a page for each link but seems very inefficient.

This question seemed very similar but it never recieved an answer: Nextjs: render content based on sidebar choice

Any help would be appreciated, thanks.

Upvotes: 0

Views: 194

Answers (1)

Andr&#233; Oliveira
Andr&#233; Oliveira

Reputation: 1121

you just need to create separated files for each page, so let's say you have an item on the menu called "Overview", you can create a pages/overview.js file, and Next.js will automatically recognize that when you navigate to youraddress.com/overview you want to open the overview component.

And to reuse the logic "around" your overview component you need to create a layout.

You would need to something like this:

// components/navbar.js

const Navbar = () => {
  return <div>This is appears everywhere!</div>;
};

export default Navbar;


 // components/Layout.js
    
import Head from "next/head";

import Navbar from "./Navbar";

const Layout = ({ children }) => {
  return (
    <div>
      <Head>
        <title>Your awesome App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Navbar />
      {children}
    </div>
  );
};

export default Layout;
    
    
 // Wrapping your index.js into your layout
import Layout from "../components/Layout";
import styles from "../styles/Home.module.css";

export default function Home() {
  return (
    <Layout>
      <div className={styles.container}>This is the home page</div>
    </Layout>
  );
}

// pages/overview.js (the name of the file is the route, so by creating overview you can access localhost:3000/overview and next.js will redirect

import Layout from "../components/Layout";
import styles from "../styles/Home.module.css";

export default function overview() {
  return (
    <Layout>
      <div className={styles.container}>This is overview page</div>
    </Layout>
  );
}

For the full source code check https://github.com/and-dutra/minimal-nextjs-layout

Upvotes: 1

Related Questions