D
D
Deodatuss2015-10-25 12:24:52
JavaScript
Deodatuss, 2015-10-25 12:24:52

How to disable rendering of a component in react.js until there is no data?

In general, when the user goes to the page, an action is launched in the componentWillMount of the root component that asks if the user is logged in, then this info is pushed into the store and the component itself reacts to the change and redirects to the login page if the user is not logged in. But with this approach, a big problem arises, namely, that before the info about the user arrives, the page has already been rendered, and this should not be. In general, if we shorten everything described above, the following question comes up: "How to prevent a component from being rendered until infa comes from the server?".
I see two options, but I don't like them:
1. Make the component render in another function, for example render2 and run it when the data arrives.
2. Push the check into componentShouldUpdate
Is there anything else?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-10-25
@Deodatuss

There is no way you can stop a component from rendering. Display the loading screen if the data has not yet arrived:

class MyComponent extends Component { 
  //...
  render() {
    const { isLoading }  = this.props;
    return isLoading ? <LoadingScreen /> : <OtherComponent />;
  }
}

As a matter of fact, such business logic does not need to be kept in components - take it out into a separate layer.

E
Edward, 2015-12-13
@edtoken

In my projects, I extend the React.Component class with my own methods (for example, to get a global context, etc., as well as manage timers, data, etc.).
In the end it looks something like this:

render(){
if(!this.ready()){ return false }
return (<div>Render done </div>);
}

in the ready method, storage is checked for the presence of data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question