Articles in this section
Category / Section

How do I change the Syncfusion light and dark themes dynamically in React?

2 mins read

Switching between light and dark themes enhances the user experience by allowing users to choose their preferred visual environment. This article demonstrates how to implement dynamic theme switching in a React application for Syncfusion components.

Include theme files

First, include the Syncfusion light and dark theme in your HTML file. Here, we have included light and dark material 3 themes.

<link href="https://cdn.syncfusion.com/ej2/24.1.41/material3.css" rel="stylesheet" id="material3">
<link href="https://cdn.syncfusion.com/ej2/24.1.41/material3-dark.css" rel="stylesheet" id="material3-dark">

Make sure that the version in the URLs matches the version of the Syncfusion React package you are using.

Enabling the Default Theme

Upon initial rendering, you should enable the default theme and disable other themes that are referenced in the HTML. You can achieve this by setting the disabled property.

useEffect(() => {
  document.getElementById("input1").checked = "true";
  setTheme("material3");
});

const setTheme = (selectedTheme) => {
  document.getElementById(selectedTheme).disabled = false;
  const otherTheme = selectedTheme == "material3" ? "material3-dark" : "material3";
  document.getElementById(otherTheme).disabled = true;
};

Theme Switching

To allow users to switch themes based on their input, you can create a function that listens for changes and updates the enabled stylesheet. The following function handleThemeChange demonstrates how to toggle between the Material 3 and Material 3 Dark themes:

const handleThemeChange = (event) => {
  const selectedTheme = event.target.value;
  setTheme(selectedTheme);
};

To use this function, you would typically have an input element such as a select dropdown or a toggle switch where the event.target.value corresponds to the theme the user wants to activate.

Explore the provided sample to see the theme switching functionality in action:

React Theme Switcher Sample

Conclusion

By following the steps outlined in this article, you can now dynamically switch between light and dark themes in your React application for Syncfusion components, providing a better user experience.

Additional References

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied