Skip to main content

Support dark and light themes

Dynatrace platform allows switching between light and dark themes. Strato components support it out of the box. If you create custom components or use custom resources, you can add light and dark theme support for them.

Custom component

You can use Strato design tokens to support theming when you create custom components. Instead of writing hard-coded CSS values like colors, or radius, you can import design tokens from @dynatrace/strato-design-tokens and use them instead of hard-coded values. It will ensure that when a user switches the theme, colors will adapt accordingly. Look at a custom card component and see the styling of the div element.

import React from "react";
import { Colors } from "@dynatrace/strato-design-tokens";

export const Card = ({ href, name }) => {
return (
<div
style={{
background: Colors.Background.Surface.Default,
}}
>
<a href={href}>{name}</a>
</div>
);
};

Note that you can use the Strato design tokens anywhere you can also use CSS. Look at the earlier example rewritten using styled components.

import React from "react";
import styled from 'styled-components';
import { Colors } from "@dynatrace/strato-design-tokens";

const StyledDiv = styled.div`
background: ${Colors.Background.Surface.Default};
`;

export const Card = ({ href, name }) => {
return (
<StyledDiv>
<a href={href}>{name}</a>
</StyledDiv>
);
};

Custom resource

You use the useCurrentTheme hook from the @dynatrace/design-system-preview library to have a custom behavior based on the user's theme. This hook returns a string value that can be light or dark based on the selected theme. The following example shows you how you can show different images based on the user's theme:

import React from "react";
import { useCurrentTheme } from "@dynatrace/strato-components-preview";

export const MyResource = () => {
const theme = useCurrentTheme();
return (
<>
{
theme === 'light' ?
<img src={'./assets/background.png'}></img>
:
<img src={'./assets/background_dark.png'}></img>
}
</>
);
};
Still have questions?
Find answers in the Dynatrace Community