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

Time:08-06

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

CodePudding user response:

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;

CodePudding user response:

Sure - particlesOptions is imported as a plain Javascript object, so you can write a function to modify (a copy of) it, e. g.

function getParticleOptions(x) {
  // Shallow copy of the original object 
  const options = {...particlesOptions};
  options.x = x; // or whatever 
  return options;
}

Then pass the returned value to the particle component.

  • Related