Useful Links:
I want to defer rendering until the Webfonts are loaded by fontfaceobserver. What would be the best practise in GatsbyJS for that?
Defer rendering component wise or the whole app?
Defer rendering component wise or the whole app?
Deferring rendering component wise. In my case it would be then the layout component.
For what i've read about the library you mentioned and with the information you provided.
You would have to transform the layout component from stateless component, to a full blown class component and for instance on componentDidMount method invoke the library. Just don't forget that every time the layout component is added it will trigger the library.
Gatsby is "just React," so you'd write this like you would any other component that needs state as @jonniebigodes noted.
It'd end up looking like something like this:
import React from 'react'
export default class Layout extends React.Component {
state = {
ready: false
}
async componentDidMount() {
await new Promise(resolve => {
// do something async here
setTimeout(resolve, 2500)
})
this.setState({
ready: true
})
}
render() {
if (!this.state.ready) {
return null;
}
return (
<div>
<h1>Fonts are ready</h1>
</div>
)
}
}
since you have an action that will be re-performed on every component mount, you may want to look into using gatsby-plugin-layout if you're using gatsby v2.
I do have to note that I think this seems to be a pretty bad practice. I don't think waiting for fonts to load and then suspending rendering is a great practice for the end user. I'd recommend checking out this article to learn more about web fonts, and in particular, check out gatsby-plugin-typography for some best practices in Gatsby.
I'm going to close this out (for now!) but please do feel free to re-open if we can assist further. Thank you!
Most helpful comment
Gatsby is "just React," so you'd write this like you would any other component that needs state as @jonniebigodes noted.
It'd end up looking like something like this:
since you have an action that will be re-performed on every component mount, you may want to look into using
gatsby-plugin-layoutif you're using gatsby v2.I do have to note that I think this seems to be a pretty bad practice. I don't think waiting for fonts to load and then suspending rendering is a great practice for the end user. I'd recommend checking out this article to learn more about web fonts, and in particular, check out gatsby-plugin-typography for some best practices in Gatsby.
I'm going to close this out (for now!) but please do feel free to re-open if we can assist further. Thank you!