Structuring Layouts in Inertia.js applications

What is the advantages of using layouts ?

In many projects, most of the pages or view extend the common features in all pages. So having all common features of all pages in one file are better user enhancement. This method can reduce time wastage, code duplication and etc. Also we can correct the codes in one place(layout file) if any error occur in common feature. Examples of layout sidebar, navigation bar and etc. Layouts are implemented in children components.

Let's develop the layout

We can create the Layout component under resources/js/Shared. Assume the name of the layout component to be Layout.vue, following code shows the content of Layout.vue

<template>
    <main>
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <button class="navbar-toggler" type="button" data-toggle="collapse"
                    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="hidden md:block">
                <div class="ml-10 flex items-baseline space-x-4">
                    <inertia-link href="/dashboard"
                                  class="bg-black-900 text-black-50 px-3 py-2 rounded-md text-sm font-medium">Dashboard
                    </inertia-link>
                    <inertia-link href="/users"
                                  class="bg-black-900 text-black-50 px-3 py-2 rounded-md text-sm font-medium">Users
                    </inertia-link>
                </div>
            </div>
        </nav>
        <article>
            <slot/>
        </article>
    </main>
</template>

<script>
export default {
    inject: ['page'],
}
</script>

Here, we can only have one root(main) under template. <inertia-link> is used for navingating links. Examples of navigation links Users and Dashboard in this post.

Import the Layout file and export the layout components where necessary

import Layout from "../../Shared/Layout";

export default {
  components: { Layout,Pagination},
}
  

Conclusion

We can avoid code duplication, time wastage and achieve flexibility through these kind of process. Also we can minimize overhead of codes as much as possible by this. If anyone needs more information please visit the official documentation:


Related articles