Check if the stylesheet is loaded and then the render items

I am developing a generic reactive app using reactive, reductive, reactive routers and reactive helmets. Each page in my application has a separate stylesheet. When the routes are changed on the client side, at first the elements are not yet styled. and within a few milliseconds my page gets ugly! I want a solution to this problem. How do I know when a stylesheet is loaded?

My container component:

render() {
        return (
            <div>
                <Helmet>
                    <title>MyTitle</title>
                    <link rel="stylesheet" href="../search-page.css"/>
                </Helmet>
                <div id="container"">
                   <MyComponents />
                </div>
            </div>
        )
    }

      

+3


source to share


1 answer


Haven't tested, but I think you can register a listener onLoad

for your tag <link />

that will set a status flag, triggering the rendering of your components.

class MyComponent extends Component {
  state = { loaded: false };
  onLoad = () => this.setState({ loaded: true });
  render() {
    return (
      <div>
        <Helmet>
          <title>MyTitle</title>
          <link rel="stylesheet" href="../search-page.css" onLoad={this.onLoad} />
        </Helmet>
        {this.state.loaded && 
          <div id="container">
            <MyComponents />
          </div>
        }
      </div>
    );
  }
}

      



Edit. Since it looks like the onLoad hook for tags is <link />

not triggered, another approach could be something like this:

class MyComponent extends Component {
  state = { loaded: false };
  componentDidMount() {
    const sheet = document.createElement('link');
    sheet.rel = 'stylesheet';
    rel.addEventListener('load', this.onLoad);
    rel.href = '../search-page.css';
  }
  onLoad = () => this.setState({ loaded: true });
  render() { /* as before */ }
}

      

0


source







All Articles