0

I am fairly new to React. I have currently made a loading screen in React with useEffect, but I'm not sure how to make it with class Components. This is my functional component which works.

const [sourceLoading, setSourceLoading] = React.useState(true);

// control when to stop loading
useEffect(() => {
  setTimeout(() => {
    setSourceLoading(false);
  }, 1000);
}, []) 

  return (
    <div>
    {sourceLoading ? (<LoadingScreen />): (
      <>


      </>
      )}
    </div>
  );

I'm currently converting the function like so, however it isn't working, and my loading screen never appears. Where am I going wrong? is componentDidMount not the correct substitution for useEffect here?

this.state = {
  sourceLoading: true,
};

this.componentDidMount = this.componentDidMount.bind(this);

componentDidMount() {
  setTimeout(() => {
    this.setState({ sourceLoading: false});
  }, 1000);
}

  render() {
    return (
      <div>
      {this.sourceLoading ? (<LoadingScreen />) : (<> 

    

       </>
      )}
      </div>
    );
  }

kxg
  • 15
  • 4

2 Answers2

0

You need to access the state in render function like

{this.state.sourceLoading ? (<LoadingScreen />) : null}
Javvy7
  • 146
  • 1
  • 8
  • 1
    Also you do not have to bind the life cycle methods this.componentDidMount = this.componentDidMount.bind(this); – Prakash S Jul 16 '21 at 13:21
0

It works for me, if you change this line:

{this.sourceLoading ? (content) : ""}
// should be
{this.state.sourceLoading ? (content) : ""}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      sourceLoading: true,
    };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        sourceLoading: false
      });
    }, 1000);
  }

  render() {
    return ( 
      <div>
        {this.state.sourceLoading ? "loading" : "not"}
      </div>
    );
  }
}

ReactDOM.render( <App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>