Runtime theming

When creating themes using reshaped.config.js, all your themes are built when you run the CLI command. You get CSS files as an output and can statically import them into your product code to apply.

In some cases, you might want your themes to be more dynamic and update as the user works with the product. Here are a few examples:

  • You want to let your users dynamically customize the theme in their browser and update it right away without building a new theme file.
  • You want to request an API that will return CSS of a theme based on the values stored on your back end.

For these cases, you can use our theming API directly in both front-end and/or back-end code.

import { getThemeCSS } from "reshaped/themes";

const css = getThemeCSS("myTheme", {
  color: {
    foregroundNeutral: { hex: "#2c3e50", hexDark: "#ecf0f1" },
  },
});

You can use the returned css value to either form a server response containing the CSS or render it directly in your React code. The theme you create becomes immediately available for the Reshaped and/or Theme providers:

function Demo() {
  const [customTheme, setCustomTheme] = React.useState(false);

  const css =
    customTheme &&
    getThemeCSS("myTheme", {
      color: {
        backgroundPrimary: { hex: "#1abc9c", hexDark: "#16a085" },
      },
    });

  return (
    <>
      {css && <style>{css}</style>}
      <Theme name={customTheme ? "myTheme" : "reshaped"}>
        <View gap={4} align="start">
          <FormControl>
            <View direction="row" gap={2}>
              <Switch
                name="theme"
                onChange={() => setCustomTheme((prev) => !prev)}
              />
              <FormControl.Label>Toggle custom theme</FormControl.Label>
            </View>
          </FormControl>
          <Button color="primary">Primary button</Button>
        </View>
      </Theme>
    </>
  );
}