Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
Set bootstrap switch component to 'checked' if mode is Dark

I have a theme for my web App in my localStorage and I want to add the checked value to the Switch component if the mode is set to 'dark',or unchecked, if the mode is 'light'. However, when I set the theme to 'dark' and refresh the page the switch turn automatically to unchecked, how can I fix that? Below there is the code:

import React, { useState,useEffect } from 'react';
import useTheme from '../custom/useTheme';

export default function Switch() {
  const[active,setActive] = useState(false);

  function handleTheme(){
    if(active === false){
      // Dark mode
      useTheme(true);
      setActive(true);

      localStorage.setItem('mode','dark');
    }else if(active === true){
      // Light mode
      useTheme(false);
      setActive(false);
      localStorage.setItem('mode','light');
    }
  };
  
  return (
    <div id='switchBox' className='form-check form-switch'>
      <input
      id="switch" 
      role="switch"
      // checked
      value={active}
      type="checkbox"
      onClick={()=> handleTheme()}
      className="form-check-input shadow-sm"
      />
      <label
      className='ms-1'
      htmlFor='switch'
      >Dark</label>
    </div>
  )
};

That's how it looks, the Dark theme is on, but the Switch is unchecked.

Dark mode on, but Switch turn off

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can achieve this by using useEffect hook with an empty array. This will trigger the logic inside once when the component is rendered. Inside you can retrieve the previously saved mode property and use it to set the current session state:

useEffect(() => {
    const isLight = localStorage.getItem('mode');
    if (isLight !== undefined) setActive(isLight);
}, [])
about 4 years ago · Juan Pablo Isaza Denunciar

0

As the above answer mentions, state is stored in memory and is lost when you refresh the page. While your solution persists the theme state to localstorage you also need to set the initial value of useState to the value stored in localstorage in order to display the correct state after refresh. You can try something like this:

const[active, setActive] = useState(false)

// Get stored data from local storage if available on first render
useEffect(() => {
    // Get stored theme mode and set it in state manager
    const storedTheme = localStorage.getItem('mode')
    if(storedTheme) {
        setActive(storedTheme)
    }
}, [])

By passing an empty array as the second parameter to useEffect this will only run on the initial render. For more information on useEffect, refer to the React docs: https://reactjs.org/docs/hooks-effect.html

about 4 years ago · Juan Pablo Isaza Denunciar

0

I solved using checked with a ternary operator, giving to it the True or False value in the case I want to... That's the correct solution !

  <input
  id="switch" 
  role="switch"
  checked={localStorage.getItem('mode') === 'dark'?(true):(false)}
  value={active}
  type="checkbox"
  onClick={()=> handleTheme()}
  className="form-check-input shadow-sm"
  />
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda