Skip to content

Instantly share code, notes, and snippets.

@Oxyrus
Created Aug 16, 2019
Embed
What would you like to do?
import React from "react";
import logo from "./logo.svg";
import "./App.css";
class App extends React.Component {
state = {
checked: localStorage.getItem("theme") === "dark" ? true : false,
theme: localStorage.getItem("theme")
};
componentDidMount() {
document
.getElementsByTagName("HTML")[0]
.setAttribute("data-theme", localStorage.getItem("theme"));
}
toggleThemeChange = () => {
const { checked } = this.state;
if (checked === false) {
localStorage.setItem("theme", "dark");
document
.getElementsByTagName("HTML")[0]
.setAttribute("data-theme", localStorage.getItem("theme"));
this.setState({
checked: true
});
} else {
localStorage.setItem("theme", "light");
document
.getElementsByTagName("HTML")[0]
.setAttribute("data-theme", localStorage.getItem("theme"));
this.setState({
checked: false
});
}
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Click para cambiar el tema</p>
<label>
<input
type="checkbox"
defaultChecked={this.state.checked}
onChange={() => this.toggleThemeChange()}
/>
</label>
</header>
</div>
);
}
}
export default App;
import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';
const App = () => {
const [checked, setChecked] = useState(localStorage.getItem("theme") === "dark" ? true : false);
useEffect(() => {
document
.getElementsByTagName("HTML")[0]
.setAttribute("data-theme", localStorage.getItem("theme"));
}, [checked]);
const toggleThemeChange = () => {
if (checked === false) {
localStorage.setItem("theme", "dark");
setChecked(true);
} else {
localStorage.setItem("theme", "light");
setChecked(false);
}
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Click para cambiar el tema</p>
<label>
<input
type="checkbox"
defaultChecked={checked}
onChange={() => toggleThemeChange()}
/>
</label>
</header>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment