How to properly load Bootstrap5's Masonry into Nuxt?
Asked Answered
W

1

2

I am trying to use the Masonry plugin with Bootstrap5 and NuxtJS. When I follow the example here https://getbootstrap.com/docs/5.0/examples/masonry/ and incorporate it into my own codesandbox, I notice that my demo is not in the correct masonry format. See the gaps? My sandbox

My example:

enter image description here

Bootstrap's example:

enter image description here

What do I need to do to get my demo into format shown on the Bootstrap Masonry example page?

Warrick answered 13/5, 2021 at 11:43 Comment(2)
I found the issue (and some instances where it work), trying to fix it.Supporter
Not sure why I didn't see this before, but I noticed error in console: 210:627 error failed to tokenize "\": true }\"...", expected attribute, ">" or "/>" parser-error for the masonry fileWarrick
S
2

I checked how to load the script from a CDN either globally or locally. It was working but at one condition: you needed to NOT start on the masonry page.
Meaning that if you loaded the app on a specific page, then moved to the one with the masonry it was working. But not if you started on this specific page. So, a pretty subpar solution.

This article was really helpful to understand how to wait until the CDN script is fully loaded: https://vueschool.io/articles/vuejs-tutorials/how-to-load-third-party-scripts-in-nuxt-js/

Then I realized that we are far better installing it directly as an NPM dependency. Therefore, I proceeded to the masonry repo. Found a great message on how to setup the whole thing in Nuxt.

And after a removal of some useless stuff and some modern dynamic import, here we are

<template>
  <main>
    <h1>Bootstrap and Masonry</h1>

    <div class="row" id="masonry">
    <!-- ... -->
  </main>
</template>

<script>
export default {
  async mounted() {
    if (process.browser) {
      let { default: Masonry } = await import('masonry-layout')
      new Masonry('#masonry', { percentPosition: true })
    }
  },
}
</script>

The final solution is looking pretty well and there is not a lot of code. On top of that, the code is properly loaded. And you can load it on a click or any other event.

Supporter answered 13/5, 2021 at 16:26 Comment(2)
is process.browser still usable in NuxtJS v2.15.8? I am getting an error that process is not defined when using your code example. Also, would it be possible to take my codesandbox example from above and update it with your answer? I'm having some issues. Thanks.Warrick
@Warrick hi, mind creating a new question?Supporter

© 2022 - 2024 — McMap. All rights reserved.