Search code examples
reactjsprimereact

How can one have a theme switcher in primereact


I would like to be in a position to switch between themes in primereact rather than import one theme and then it affects my whole app and I don't have an option to switch between dark or light mode.


Solution

  • I couldn't make it work with their provided function https://primereact.org/theming/#switchthemes

    I have use useEffect for my case which changes theme dark <-> light based on prop.

    First I copied the themes I wanted to the react vite public folder root. I named them light.css and dark.css. Then in useEffect I manipulated DOM:

      useEffect(() => {
        const link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = `${props.mode}.css`;
        document.head.appendChild(link);
        return () => {
          document.head.removeChild(link);
        };
      }, [props.mode]);
    

    Now it works when props.mode change from light to dark and vice versa.