Question T19776
Visible to All Users

Changing theme dynamically

created 4 months ago (modified 4 months ago)

Hi, I was wondering if you could help, we are in the process of integrating SurveyJS into one of our products which has a dark/light mode switcher on the header. When they change to dark mode everything updates reactively, but surveyJS doesn't by default. How can I update the theme dynamically?

The following code works fine on page load

Code
//this bit works fine const formDefinition = { ... }; const survey = new Survey.Model(formDefinition); const globalTheme = 'light'; //this comes from some logic in our page header, light|dark const getSurveyJSTheme = function (ourTheme) { let theme = {}; if (ourTheme == 'dark') { theme = SurveyTheme.DefaultDark; } return theme; } const surveyJSTheme = getSurveyJSTheme(globalTheme); survey.applyTheme(surveyJSTheme); $("#form-viewer").Survey({ model: survey });

My question is how do I update it when it changes dynamically?

Code
//this function is triggered by changing the theme in our global header function onChangeGlobalHeader(newTheme){ const newSurveyJSTheme = getSurveyJSTheme(newTheme); // ---- WHAT NEEDS TO GO HERE? ----- }

Thanks for your help
Gavin

Answers approved by surveyjs Support

created 4 months ago (modified 4 months ago)

Hello Gavin,
You can apply a Light or Dark survey theme depending on your custom parameter:

JavaScript
survey.applyTheme(isDarkTheme ? SurveyTheme.DefaultDark : SurveyTheme.DefaultLight);

Clipboard-File-2.png
Consider the following SurveyComponent.jsx code:

JavaScript
import React, { useState, useEffect } from "react"; import { Model } from "survey-core"; import { Survey } from "survey-react-ui"; import "survey-core/defaultV2.min.css"; import * as SurveyTheme from "survey-core/themes"; import "./index.css"; import { json } from "./json"; function SurveyComponent() { const [isDarkTheme, setIsDarkTheme] = useState(false); const [survey, setSurvey] = useState(null); useEffect(() => { const initialSurvey = new Model(json); initialSurvey.onComplete.add((sender, options) => { console.log(JSON.stringify(sender.data, null, 3)); }); setSurvey(initialSurvey); initialSurvey.applyTheme( isDarkTheme ? SurveyTheme.DefaultDark : SurveyTheme.DefaultLight ); }, []); useEffect(() => { if (survey) { survey.applyTheme( isDarkTheme ? SurveyTheme.DefaultDark : SurveyTheme.DefaultLight ); } }, [isDarkTheme, survey]); const handleThemeChange = (event) => { setIsDarkTheme(event.target.checked); }; return ( <div> <label> <input type="checkbox" checked={isDarkTheme} onChange={handleThemeChange} /> Enable Dark Theme </label> {survey ? <Survey model={survey} /> : <p>Loading survey...</p>} </div> ); } export default SurveyComponent;

View CodeSandbox

Let me know if you have further questions.