Search code examples
javascriptreactjsfunctionreturncomponents

returning component inside function not working


I've a component which i'm rendering by considering some conditions. It's done as follows

const Test = () => {
    return <div className="text_align_center white_color">
        <span><i className="fa fa-exclamation-triangle" aria-hidden="true"></i>
            No internet connection. Please check your connection settings and try again
        </span>
    </div>
}

function checkInternetConnection(){

    isOnline().then(online => {

       if(online === true){

           console.log("Came in here")

            return <Test/>

        }

    });
}

Then i'm calling my function as follows

const App = () => (
    <div className="ui container">

        {checkInternetConnection()}
);

But the issue is eventhough i'm getting the console log inside checkInternetConnection function, the returned component is not appearing. What can be cause of this?


Solution

  • Your <Test/> is being returned by the then callback function, not your checkInternetConnection function. Because you are conditionally rendering based on some asynchronous operation, you need to take a different approach in order for your component to update correctly.

    One idea is to turn your stateless component into a stateful component by making it a class, and calling setState when your promise resolves:

    import React from 'react';
    
    class App extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = {
                isOnline: false // set initial state to false 
            };
        }
    
        componentDidMount() {
            isOnline().then(online => {
                this.setState({
                    isOnline: true; // call setState to update state and rerender App
                });
            });
        }
    
        render() { // use inline expression to conditionally show <Test/> if isOnline is true
    
            return (
    
                <div className="ui container">
    
                  { this.state.isOnline && <Test /> }
    
                </div>
            );
        }
    }