score:7
fouc
fouc - so called flash of unstyled content can be as very problematic as so many tries of solving this issue.
to the point
let's consider following configuration of routing (react-router):
...
<pagelayout>
<switch>
<route exact path='/' component={home} />
<route exact path='/example' component={example} />
<switch>
</pagelayout>
...
where pagelayout
is a simple hoc, containing div wrapper with page-layout
class and returning it's children.
now, let's focus on the component rendering based on route. usually you would use as component
prop a react compoment
. but in our case we need to get it dynamically, to apply feature which helps us to avoid fouc. so our code will look like this:
import asyncroute from './asyncroute'
const home = asyncroute(() => import('./home'))
const example = asyncroute(() => import('./example'))
...
<pagelayout>
<switch>
<route exact path='/' component={home} />
<route exact path='/example' component={example} />
<switch>
</pagelayout>
...
to clarify let's also show how asyncroute.js
module looks like:
import react, { component } from 'react'
import proptypes from 'prop-types'
import loader from 'components/loader'
class asyncimport extends component {
static proptypes = {
load: proptypes.func.isrequired,
children: proptypes.node.isrequired
}
state = {
component: null
}
togglefoucclass () {
const root = document.getelementbyid('react-app')
if (root.hasclass('fouc')) {
root.removeclass('fouc')
} else {
root.addclass('fouc')
}
}
componentwillmount () {
this.togglefoucclass()
}
componentdidmount () {
this.props.load()
.then((component) => {
settimeout(() => this.togglefoucclass(), 0)
this.setstate(() => ({
component: component.default
}))
})
}
render () {
return this.props.children(this.state.component)
}
}
const asyncroute = (importfunc) =>
(props) => (
<asyncimport load={importfunc}>
{(component) => {
return component === null
? <loader loading />
: <component {...props} />
}}
</asyncimport>
)
export default asyncroute
hasclass
,addclass
,removeclass
are polyfills which operates on dom class attribute.
loader
is a custom component which shows spinner.
why settimeout
?
just because we need to remove fouc
class in the second tick. otherwise it would happen in the same as rendering the component. so it won't work.
as you can see in the asyncimport
component we modify react root container by adding fouc
class. so html for clarity:
<html lang="en">
<head></head>
<body>
<div id="react-app"></div>
</body>
</html>
and another piece of puzzle:
#react-app.fouc
.page-layout *
visibility: hidden
sass to apply when importing of specific component (ie.: home
, example
) takes place.
why not display: none
?
because we want to have all components which rely on parent width, height or any other css rule to be properly rendered.
how it works?
the main assumption was to hide all elements until compoment gets ready to show us rendered content. first it fires asyncroute
function which shows us loader
until component
mounts and renders. in the meantime in asyncimport
we switch visibility of content by using a class fouc
on react root dom element. when everything loads, it's time to show everything up, so we remove that class.
hope that helps!
thanks to
this article, which idea of dynamic import has been taken (i think) from react-loadable.
source
Source: stackoverflow.com
Related Query
- Minified React error #152 - how to resolve this?
- How to resolve "Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operat....." with respect to React JS?
- how to resolve a react native EventEmitterListener warning
- How to resolve module name conflict in react native
- How to resolve `this` in converting React module to ES6 class
- How to resolve CORS error in REACT with ASP.NET Core
- How to resolve a promise after react hooks setState complete?
- How to fix unable to resolve module react redux hooks\useDispatch?
- How do I resolve the React app error for npm run build "Failed to compile. Failed to minify the bundle."?
- How to resolve 401 error in react js using redux.?
- How to fix Module not found: Can't resolve '@heroicons/react/solid' in react app?
- How to resolve the "Invalid hook call" error in react
- how to resolve React error Module build failed (from ./node_modules/babel-loader/lib/index.js):
- How to resolve "Cannot find module" Error when testing react components with mocha
- How to resolve nested React components into a tree of elements?
- How to resolve FOUC in React.js
- How to resolve 'deletePerson is not a function' inside onClick in react js?
- how to resolve Adjacent JSX elements must be wrapped in an enclosing tag issue in React
- How to Resolve Failed to load config "prettier" to extend from. in react Js
- How to resolve undefined match props in React and React-router
- How to resolve Typescript error -- mapbox-gl & React hooks
- How to resolve an url by fetch & redirect without refresh with react
- Error with WEB3js - NodeJs.utils in vite react ts app - How to resolve TypeError: callbackify is not a function
- How to resolve these TypeScript errors when using React refs?
- how to resolve typescript error on React app
- How to Resolve Memory Leak and Cancel All Subscriptions Error in React App?
- How to Make React Router Resolve within a nested path
- How to resolve `require` aliases built with Webpack, for React Unit tests?
- How to resolve " Cannot read property 'map' of undefined" error in React Js
- How to resolve npm ERR! ERESOLVE unable to resolve dependency tree - simple react lightbox?
More Query from same tag
- Display and Map Multiple Keys and its object data
- React hook: Pass grid's object to parent component
- Dynamically generating site info based on the URL used to get there
- How to remove className in ReactJS when page load?
- Can't figure out how to use this lightbox component i found online
- How to write test case using Jest for Yup.isValid function?
- The reducer updates apposArrayProp but Redux doesn't update my view
- React update setState convert String to Array
- Adding brackets [] to the attribute in setState
- How to set headers with axios
- How do I dynamically set HTML5 data- attributes using react?
- React Animations with VelocityJS
- How to update React state without knowing object key?
- Displaying one value and sending another to backend with HTML <select> and <option> tags
- How will my React.render function access external javascript file containing react code?
- Is there a way to pass a generic type to the reducer used in react useReducer hook?
- renderRoutes and the location property on <Switch>
- Hide collapse navbar after link click, react-redux, react-bootstrap
- Running a child component with a function in parent component
- Cannot read property 'someProperty' of undefined in react
- multiple conditional renderings inside a map function
- How fetch local data with axios?
- render function is not rendering items
- ReactJs: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`
- NULL value returned when trying to fetch data from solidity smart contract from react js
- How to stretch parent element width in layout with ant-design
- How to get only one value in a variable of parent component, by selecting and switching to any of the option in reactjs?
- How To Count Number of Documents in a Collection in Firebase Firestore With a WHERE query in react.js
- How to access a parent's current state from function passed to child
- NextJS redirect user back to the router came from after authentication