5

I'm developing universal react application using react, redux, react-router and react-helmet. Each page in my application has seperated stylesheet. When routes change in client side, at first, the elements have no style yet. and for a few milliseconds, my page gets ugly! I want a solution for this problem . How can I know when stylesheet 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>
        )
    }
Sepehr
  • 314
  • 5
  • 21
  • 2
    Place stylesheets in the website `` tag. Then all styles get loaded before the `HTML`. – Red Jul 31 '17 at 07:40
  • @Red I use Helmet so my stylesheets go in the automatic. – Sepehr Jul 31 '17 at 07:44
  • As an alternative for loading styles with `helmet` I suggest using `isomorphic-style-loader` https://github.com/kriasoft/isomorphic-style-loader – Everettss Jul 31 '17 at 08:26

1 Answers1

0

Haven't tested it, but I think you can register an onLoad listener for your <link /> tag that will set a state 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 <link /> tags doesn't trigger, a different 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 */ }
}
Kris Selbekk
  • 7,438
  • 7
  • 46
  • 73