layout.js file in Next Js

  • In Next.js, the layout.js file is a custom component used for creating a layout template that can be reused across multiple pages in your application. It helps you define a consistent structure and appearance for your pages by encapsulating common elements like headers, footers, navigation menus, and other components that should appear on every page.
  • The layout.js file typically resides in the components directory of your Next.js project. It's a regular JavaScript or TypeScript file that exports a React component. Here's a basic example of a layout.js file:


    import Link from "next/link";

    export default function Layout({ children }) {
        return (<>
            <ul>
                <li>
                    <Link href="/about/maleabout">Male About</Link>
                </li>

                <li>
                    <Link href="/about/femaleabout">Female About</Link>
                </li>
                <li>
                    <Link href="/about"> About</Link>
                </li>
            </ul>

            {children}
        </>)
    }


  • Conditionally Show common component in layout.js

    "use client"
    import Link from "next/link";
    import { usePathname } from "next/navigation";

    export default function Layout({ children }) {
        const pathname = usePathname()
        console.log(pathname)
        return (<>
            {pathname !== "/about/femaleabout" && (<>
                <ul>
                    <li>
                        <Link href="/about/maleabout">Male About</Link>
                    </li>

                    <li>
                        <Link href="/about/femaleabout">Female About</Link>
                    </li>
                    <li>
                        <Link href="/about"> About</Link>
                    </li>
                </ul>
            </>)}

            {children}
        </>)
    }




No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...