Masonry(cascading grid layout library) script loading only after editing and saving a file in VS Code in React

44 views Asked by At

first post here. I am trying to create a Masonry(https://masonry.desandro.com/) photo portfolio, so far I got it working only by accident - editing the file and saving it made Masonry work correctly e.g. loading the scrip and changing the position of children elements. I am stumbling about as I am quite new at this, so any pointers would be appreciated.

The problem is, it works only after editing and saving the file I try to display, in my case it's PortfolioPortrait module. After adding anything(a class to any element for example) and saving the masonry snaps into place and becomes responsive.

I tried to write the classes, CSS styles, created Masonry.js module, installed Masonry the npm way. I assume that the problem is in the useEffect hook not loading on the start. Here's the Masondry.js

import React, { useEffect } from "react";

function Masonry() {
  useEffect(() => {
    const script = document.createElement("script");

    script.src = "https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.js";
    script.async = true;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  });

  return(

  );
}

and here's the module

import React from "react";
import Masonry from "masonry-layout";

const PortfolioPortrait = () => {
  const grid = document.querySelector(".grid_");
  const msnry = new Masonry(grid, {
    itemSelector: ".grid-item",
    columnWidth: ".grid-sizer",
    percentPosition: true,
  });
  const imgListFirst = [...new Array(10)].map(
    (number, index) => `/photos/photowalk/photowalk (${index + 1}).jpg`
  );
  return (
    <div className="grid_">
      <div className="grid-sizer"></div>
      <div data-masonry='{ "itemSelector": ".grid-item"}'>
        {imgListFirst.map((imgUrl, index) => {
          return (
            <div key={index} className="grid-item">
              <img src={imgUrl} alt="collection" />
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default PortfolioPortrait;

0

There are 0 answers