-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(v2): refactor dark toggle into a hook (#1899)
* change(v2): refactor dark toggle into a theme * follow how themes resolve files * let theme hook to pick up default theme by itself
- Loading branch information
Showing
3 changed files
with
54 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
packages/docusaurus-theme-classic/src/theme/hooks/theme.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/** | ||
* 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.querySelector('html').getAttribute('data-theme') | ||
: '', | ||
); | ||
React.useEffect(() => { | ||
try { | ||
setTheme(localStorage.getItem('theme')); | ||
} 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; |