Get URL pathname in nextjs Coding Filters

Conditionally Render Components Based on Pathname in Next.js

In Next.js, you can conditionally render components based on the current route, which is particularly useful for showing or hiding elements like a header depending on the page. This is often needed when you want to exclude a header from pages like a signin or signup page.

Next.js offers two primary ways to access the router object: using the useRouter hook (for functional components) and withRouter (for class components).

Using withRouter for Class Components

If you’re working with class components, you can use the withRouter higher-order component to inject the router prop into your component. Here’s how you can conditionally render a header based on the current pathname:

#jsx #nextjs
import { withRouter } from 'next/router';

class MyApp extends React.Component {
    render() {
        const { router } = this.props;

        // Check if the current pathname is '/signin'
        const shouldHideHeader = router.pathname === '/signin';

        return (
            <Layout>
                {/* Conditionally render the header */}
                {!shouldHideHeader && <Header />}
                <Component {...pageProps} />
            </Layout>
        );
    }
}

export default withRouter(MyApp);  // Wrap your component with withRouter

Here, withRouter adds the router prop, giving you access to router.pathname. You can then check if the pathname is /signin and decide whether to render the Header component.

Using useRouter for Functional Components

For functional components, you can use the useRouter hook to access the router object. Here’s an example:

#jsx #nextjs
import { useRouter } from 'next/router';

const MyApp = ({ Component, pageProps }) => {
    const router = useRouter();

    // Check if the current pathname is '/signin'
    const shouldHideHeader = router.pathname === '/signin';

    return (
        <Layout>
            {/* Conditionally render the header */}
            {!shouldHideHeader && <Header />}
            <Component {...pageProps} />
        </Layout>
    );
};

export default MyApp;

The logic remains the same: you check router.pathname and conditionally render the header if the pathname is not /signin.

Review

By using withRouter in class components or useRouter in functional components, you can easily access the current pathname and use that to conditionally render components like a header. This allows you to have a flexible layout structure where specific pages (such as signin or signup) can omit certain components.

Author

  • theaamirlatif

    Frontend Web Dev and UI/UX Engineer, cross-browser, responsive design, user interaction, web accessibility, and client-side optimization in React, WP, Apps Dev.

    View all posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *