Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load a stylesheet with React

Tags:

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 page the user is editing. How could I do something like this with React?

My app is fully React, isomorphic, running on Koa. My basic component heirarchy for the page in question looks something like this:

App.jsx (has `<head>` tag) └── Layout.jsx (dictates page structure, sidebars, etc.)     └── EditLandingPage.jsx (shows the landing page in edit mode) 

Data for the landing page (including the path of the stylesheet to load) is fetched asynchronously in EditLandingPage in ComponentDidMount.

Let me know if you need any additional info. Would love to get this figured out!

Bonus: I'd also like to unload the stylesheet when navigating away from the page, which I assume I can do the reverse of whatever answer comes my way in ComponentWillUnmount, right?

like image 658
neezer Avatar asked Feb 07 '15 19:02

neezer


2 Answers

Just update stylesheet's path that you want to be dynamically loaded by using react's state.

import * as React from 'react';  export default class MainPage extends React.Component{     constructor(props){         super(props);         this.state = {stylePath: 'style1.css'};     }      handleButtonClick(){         this.setState({stylePath: 'style2.css'});     }      render(){         return (             <div>                 <link rel="stylesheet" type="text/css" href={this.state.stylePath} />                 <button type="button" onClick={this.handleButtonClick.bind(this)}>Click to update stylesheet</button>             </div>         )     } }; 

Also, I have implemented it as react component. You can install via npm install react-dynamic-style-loader.
Check my github repository to examine:
https://github.com/burakhanalkan/react-dynamic-style-loader

like image 65
burak Avatar answered Sep 19 '22 11:09

burak


I think that Burakhan answer is correct but it is weird to load <Link href = "" /> 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 (     <div>       <button type="button" onClick={handleButtonClick}>         Click to update stylesheet       </button>     </div>   ); }; 
like image 31
Mohamed Magdy Avatar answered Sep 20 '22 11:09

Mohamed Magdy