Rendering content conditionally in ReactJS

In State in ReactJS, we have seen how to fetch the data in State object for the Component. But we have not seen how to display error message if latitude and longitude are not available.

Copy and paste below code in index.js file.

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    constructor(props) {
        // super() is used to call the constructor os 
        super(props);

        // this is the only time we use direct assignment to state, 
        // that is at the initialization time
        this.state = { lat: null, long: null, errMsg:'' };

        window.navigator.geolocation.getCurrentPosition(
            position => {
                // update state data using setState() method
                this.setState({ lat: position.coords.latitude, long: position.coords.longitude });
            },
            err => {
                this.setState({ errMsg: err.message });
            }
        );
    }
    render() {
        // When Latitude and longitude is not fetched, we will show an error message
        if(this.state.errMsg && !this.state.long){
            return <div><b>Error: </b>{this.state.errMsg}</div>
        }

        // When we know Latitude and Longitude, then their values will be displayed
        if(!this.state.errMsg && this.state.long){
            return(
                <div>
                    <b>Latitude: </b>{this.state.lat}<br />
                    <b>Longitude: </b>{this.state.long}
                </div>
            );
        }

        // When the values are still loading
        if(!this.state.errMsg && !this.state.long){
            return<div>Loading...</div>
        }
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

The output will be based on data fetched.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started