React.js and Isotope.js

前端 未结 8 1785

I\'m checking out React.js and trying to figure out how this library can work together with Isotope.js. The documentation of React says that it plays nicely with other libra

8条回答
  •  情书的邮戳
    2020-12-30 03:58

    My solution with useState and useEffect hooks, also works with dynamically generated filter keys and items. The trick is to initialize Isotope after the component is mounted, and call its "arrange" method everytime the filter keyword changes. You can achieve the same with componentDidMount and componentDidUpdate in a class component.

    Demo: https://codepen.io/ilovepku/pen/zYYKaYy

    const IsotopeReact = () => {
      // store the isotope object in one state
      const [isotope, setIsotope] = React.useState(null);
      // store the filter keyword in another state
      const [filterKey, setFilterKey] = React.useState("*");
    
      // initialize an Isotope object with configs
      React.useEffect(() => {
        setIsotope(
          new Isotope(".filter-container", {
            itemSelector: ".filter-item",
            layoutMode: "fitRows"
          })
        );
      }, []);
    
      // handling filter key change
      React.useEffect(
        () => {
          if (isotope) {
            filterKey === "*"
              ? isotope.arrange({ filter: `*` })
            : isotope.arrange({ filter: `.${filterKey}` });
          }
        },
        [isotope, filterKey]
      );
    
      return (
        <>
          
    • setFilterKey("*")}>Show Both
    • setFilterKey("vege")}>Show Veges
    • setFilterKey("fruit")}>Show Fruits

      Cucumber
      Apple
      Orange
      Tomato
    ); };

提交回复
热议问题