Reputation: 7105
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?
Upvotes: 0
Views: 613
Reputation: 76
Since isOnline()
has a .then()
clause I assume it is an asynchronous Promise?
If that is the case, then that is your culprit. The component will not re-render when the promise returns as React only renders when state changes, which is not the case here.
To get the behavior you describe do the rendering of the Test component based on a state variable and set it in your .then()
when the promise returns.
Upvotes: 1
Reputation: 5456
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>
);
}
}
Upvotes: 4