Dynamically load a stylesheet with React

前端 未结 5 1663
夕颜
夕颜 2020-11-29 02:16

I\'m building a CMS system for managing marketing landing pages. On the \"Edit Landing Page\" view, I want to be able to load the associated stylesheet for whichever landing

5条回答
  •  被撕碎了的回忆
    2020-11-29 02:33

    I think that Burakhan answer is correct but it is weird to load inside the body tag. That's why I think it should be modified to the following [ I use React hooks]:

    import * as React from 'react';
    export default MainPage = (props) => {
      const [ stylePath, setStylePath ] = useState("style1.css");
        
      const handleButtonClick = () => {
        setStylePath({stylePath: 'style2.css'});
      }
    
      useEffect(() => {
        var head = document.head;
        var link = document.createElement("link");
    
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = stylePath;
    
        head.appendChild(link);
    
        return () => { head.removeChild(link); }
    
      }, [stylePath]);
    
      return (
        
    ); };

提交回复
热议问题