I have an image with a white background, which looks off on docusaurus dark theme, so I want to detect when the user changes theme so I use a different image.
Is it possible to detect if docusaurus is in light or dark mode?
5.1k Views Asked by Adegoke Temitope At
6
There are 6 best solutions below
0
On
br8dy's answer above works in development-mode, but will throw an error when you try to build the project - Docusaurus will complain that the component doesn't exist within a component (displaying a reference to this part of the docs).
The solution is to use BrowserOnly, as documented here. Explicitly, you need to change this:
const ImageSwitcher = ({lightImageSrc, darkImageSrc}) => {
const { isDarkTheme } = useThemeContext();
return (
<img src={isDarkTheme ? darkImageSrc : lightImageSrc} alt="Example banner" />
)
}
To something like this:
const ImageSwitcher = ({lightImageSrc, darkImageSrc, altText}) => {
return (
<BrowserOnly fallback={<img src={darkImageSrc} alt={altText} />}>
{() => {
const { isDarkTheme } = useThemeContext();
const imgSrc = isDarkTheme ? darkImgSrc : lightImgSrc;
const fullImgSrc = useBaseUrl(imgSrc);
return (
<img src={fullImgSrc} alt={altText} />
)
}}
</BrowserOnly>
)
}
0
On
Instead of creating a custom component, you can use Themed Images:
import ThemedImage from '@theme/ThemedImage';
import useBaseUrl from '@docusaurus/useBaseUrl';
<ThemedImage
alt="Docusaurus themed image"
sources={{
light: useBaseUrl('/img/docusaurus_light.svg'),
dark: useBaseUrl('/img/docusaurus_dark.svg'),
}}
/>;
With it, you will not have the following error:
`useThemeContext` is used outside of `Layout` Component.
0
On
Now it is possible with the following, in a .mdx file:
import ThemedImage from '@theme/ThemedImage';
<ThemedImage
alt="Docusaurus themed image"
sources={{
light: useBaseUrl('/img/docusaurus_light.svg'),
dark: useBaseUrl('/img/docusaurus_dark.svg'),
}}
/>;
Reference: Docusaurus. Themed images
1
On
for version 2.0.0-beta.15, you can get current theme mode like this:
import { useColorMode } from '@docusaurus/theme-common';
// ^^ I don't think it's in the docs yet, but I get the referencet from here
// https://github.com/rohit-gohri/redocusaurus/issues/116
const Component = () => {
const { isDarkTheme } = useColorMode();
return <div>{isDarkTheme ? 'Dark' : 'Light'}</div>;
};
If you are using the classic theme, you can leverage the
useThemeContexthook to detect the current color mode setting. Since documents support MDX, you can create a component that conditionally displays the appropriate image based on the color mode value provided by the theme context. Here is a basic example.This suggestion is based on using the following docusaurus versions:
ImageSwitcher Component File
Create a react component that can be imported to your documentation
Documentation Markdown File
Import the component into your documentation and pass the appropiate image sources to the component.