mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-25 15:07:17 +02:00
* refactor(v2): toggle data-theme with vanilla js instead of react helmet * use document documentElement
46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
/**
|
|
* Copyright (c) 2017-present, Facebook, Inc.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*/
|
|
import * as React from 'react';
|
|
|
|
const useTheme = () => {
|
|
const [theme, setTheme] = React.useState(
|
|
typeof document !== 'undefined'
|
|
? document.documentElement.getAttribute('data-theme')
|
|
: '',
|
|
);
|
|
|
|
React.useEffect(() => {
|
|
document.documentElement.setAttribute('data-theme', theme);
|
|
}, [theme]);
|
|
|
|
React.useEffect(() => {
|
|
try {
|
|
const localStorageTheme = localStorage.getItem('theme');
|
|
if (localStorageTheme !== null) {
|
|
setTheme(localStorageTheme);
|
|
}
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}, [setTheme]);
|
|
|
|
const setThemeSyncWithLocalStorage = React.useCallback(
|
|
nextTheme => {
|
|
try {
|
|
localStorage.setItem('theme', nextTheme);
|
|
setTheme(nextTheme);
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
},
|
|
[setTheme],
|
|
);
|
|
|
|
return [theme, setThemeSyncWithLocalStorage];
|
|
};
|
|
|
|
export default useTheme;
|