javascriptreactjssassparticles.js

Is there anyway to use data from a json file conditionally?


I am using React and Sass on my project and a library called ParticleJs as background and I'm hoping to achieve dark mode feature on my project where when a user wants it, the data in ParticleJS json file is changed.

Here's a snippet of the json file I'd like to change conditionally specifically, bg.color.value

"background": {
    "color": {
      "value": "#edf2f8"
    },
    "position": "50% 50%",
    "repeat": "no-repeat",
    "size": "20%"
  },

Here is the whole ParticleJS.jsx file:

import Particles from "react-tsparticles";
import { loadFull } from "tsparticles";
import particlesOptions from "./particles.json";
import React, { useCallback } from "react";

const ParticleBackground = () => {
  const particlesInit = useCallback((main) => {
    loadFull(main);
  }, []);

  const particlesLoaded = (container) => {
    console.log(container);
  };

  return (
    <Particles
      init={particlesInit}
      loaded={particlesLoaded}
      options={particlesOptions}
    />
  );
};

export default ParticleBackground;

Is there any other way that I can do it than creating another js folder (to maybe call two ParticleJS components conditionally) or maybe create another json file?

Thank you in advance


Solution

  • According to the docs you don't need to pass JSON into the options prop you can just pass a javascript opject. If you include a "useState" variable in the object for the bg color (for example) you can update it as you need.

    import Particles from "react-tsparticles";
    import { loadFull } from "tsparticles";
    import React, { useCallback, useState} from "react";
    
     const ParticleBackground = () => {
      const particlesInit = useCallback((main) => {
        loadFull(main);
      }, []);
    
      const particlesLoaded = (container) => {
        console.log(container);
      };
    
      const [bgColor, setBgColor] = useState('#edf2f8');
    
     //call setBgColor when you want to update the bg
    
      return (
        <Particles
          init={particlesInit}
          loaded={particlesLoaded}
          options={{
             background: {
                color: {
                   value: bgColor
                },
                position: "50% 50%",
                repeat: "no-repeat",
                size: "20%"
            }
           }}
        />
      );
    };
    
    export default ParticleBackground;