Home > Software engineering >  ReactJs: Intial Component Rendering doesn't seems to work
ReactJs: Intial Component Rendering doesn't seems to work

Time:07-16

I'm working on a project and came across this issue that first time when component is rendered, it doesn't shows anything on the screen. Then componentDidMount is invoked and after that something is visible on the screen.

My App Component

class App extends React.Component {
  state={loading: true};

  componentDidMount(){
    alert("Inside did mount");
    this.setState({loading: false});
  }

  render() {
    alert(this.state.loading);
    if (this.state.loading) {
      return <div>Loading...</div>;
    }
    
    return(
      <div>After ComponentDid Mount !</div>
    )
  }
}

In above code, initially Loading... should be visible on the screen for the first time. But this isn't happening.

Am I doing some kind of mistake here ? Is there any way to show Loading... on the screen first and after that componentDidMount will run ?

CodePudding user response:

your state for a class component needs to be inside a constructor.

constructor(props) {
 super(props)
 this.state = {your state}
}

Now that will allow you reference it as the component using (this)

It’s currently a normal variable and isn’t used as this.state but just state but that means changes to this variable may not reflect to changes to the pages. Further reading on this:

https://reactjs.org/docs/hooks-state.html

Also you may want to begin using functional components the way you wrote your render()

In my experience It’s preferable to have a single return in render and then from that return call upon functions and variables to render the page differently

CodePudding user response:

It mounts the component fast so you can't see the loading text. You can use the setTimeout function to mimic remote server requests and latency.

import React from "react";

class App extends React.Component {
  state = { loading: true };

  componentDidMount() {
    setTimeout(() => {
      this.setState({ loading: false });
    }, 5000);
  }

  render() {
    if (this.state.loading) {
      return <div>Loading...</div>;
    }

    return <div>After ComponentDid Mount !</div>;
  }
}

export default App;
  • Related