I am trying to change the color of my particles background and link dynamically.The theme only changes after I refresh the page for some reason.
this is my darkMode component:
import React from 'react';
import { ReactComponent as Sun } from './Sun.svg';
import { ReactComponent as Moon } from './Moon.svg';
import './DarkMode.css';
const DarkMode = () => {
const setDarkMode = () => {
document.querySelector('body').setAttribute('data-theme', 'dark');
localStorage.setItem('selectedTheme', 'dark');
};
const setLightMode = () => {
document.querySelector('body').setAttribute('data-theme', 'light');
localStorage.setItem('selectedTheme', 'light');
};
const selectedTheme = localStorage.getItem('selectedTheme');
if (selectedTheme === 'dark') setDarkMode();
const toggleTheme = (e) => {
if (e.target.checked) setDarkMode();
else setLightMode();
};
return (
<div className="dark_mode">
<input
className="dark_mode_input"
type="checkbox"
id="darkmode-toggle"
onChange={toggleTheme}
defaultChecked={selectedTheme === 'dark'}
/>
<label className="dark_mode_label" for="darkmode-toggle">
<Sun />
<Moon />
</label>
</div>
);
};
export default DarkMode;
and this is my particle component:
import React, { useCallback, useEffect, useState } from 'react';
import Particles from 'react-tsparticles';
import { loadSlim } from 'tsparticles-slim';
import '../style/ParticlesBackground.css';
const ParticlesBackground = () => {
const [theme, setTheme] = useState('dark');
console.log(theme);
useEffect(() => {
const savedTheme = localStorage.getItem('selectedTheme');
if (savedTheme) {
setTheme(savedTheme);
}
}, []);
const particlesInit = useCallback(async (engine) => {
await loadSlim(engine);
}, []);
const particlesLoaded = useCallback((container) => {
console.log(container);
}, []);
const calculateThemeColor = (darkColor, lightColor) => {
return theme === 'dark' ? darkColor : lightColor;
};
const particleColor = calculateThemeColor('#7e7c73', '#2e2e2e');
const linkColor = calculateThemeColor('#e61717', '#140005');
const bodyBackground = calculateThemeColor('#040720', '#454545');
const particleOptions = {
background: {
color: {
value: bodyBackground,
},
},
//OTHER PARTICLE OPTIONS
particles: {
color: {
value: particleColor,
},
links: {
color: linkColor,
distance: 165,
enable: true,
opacity: 0.6,
width: 1.3,
//OTHER PARTICLE OPTIONS
};
console.log(particleOptions);
return (
<div>
<Particles
id="tsparticles"
init={particlesInit}
loaded={particlesLoaded}
options={particleOptions}
/>
</div>
);
};
export default ParticlesBackground;
The localStorage variable doess change but visually nothing is being changed unless I refresh the page.