Search code examples
javascripthtmlreactjscomponentslifecycle

Loading Div before render Page (React)


I have an page but it's heavy, and react still spend some seconds to load all components, i would like to put an div with greater z-index to overlap it. The problem:

componentWillMount prints 'test' on console, but do not render the div:

componentWillMount() {
    return (
        <div className={this.props.classes.modalLoading}>
            TESTE
        </div>
    )
}

note css= 100vw, 100vh, bg: black, color: white

It's possible dismember in another component 'Loader' to use in another places? (console log don't work)

render() {
    const { classes } = this.props
    return (
        <div className={classes.root} ref={'oi'}>
            <LayoutCard {...this.props}/>
        </div>
    )
}

componentDidMount() {
    {console.log('teste 3')}
}

Solution

  • Well, that is not how react works :) It renders the JSX that is returned from the render() method.. the return value of the componentWillMount() is not associated with the render method.

    If you want a loader you should set a state on the main component to swap between a return, that returns a loader div and the return that returns your page content. I'm not sure what you mean by 'loading' in react. Maybe any sync ajax stuff? Set a state after it finished.

    if(this.state.loaded) {
        return <Loader />
    } else {
        return <Content />
    }
    

    If you mean things like fonts, stylesheets and images... well thats its a duplicate of

    Show loading icon before first react app initialization