Dominik Krzywiecki
Dominik Krzywiecki

Reputation: 425

Hide loading icon when all children are rendered

I have some trivial (I guess) problem regarding rendering in react but can not solve it and can not find any solution.

My problem is that I have component which is wrapper for some entries. Something like:

class MyWrapper extends Component {
  renderItems() {
    return (
        {this.props.items.map(item => (
         <ItemComponent item={item} />
        ))}
    );
  }

  renderMessage() {
    return (<p>No items to show</p>);
  }

  render() {
   <div>
     {this.props.length
        ? this.renderItems()
        : this.renderMessage()
     } 
   </div>
  }
}

Usually I got in this.props.items bunch of items so render all of theme took a time. This is why I would like to show message like Loading items... until render all items is finished. Then this message should disappear.

Thanks for help in advance!

Upvotes: 3

Views: 196

Answers (3)

Sam
Sam

Reputation: 592

Here's a quick-and-dirty solution. Ideally the concept will be what you're looking for and you can clean it up as desired.

(Also, it's my understanding that the issue is that props.items is huge, and that the map procedure simply takes a while)

class MyWrapper extends Component {
  constructor(props) {
    super(props);
    this.state = { items: [] }
  }

  componentDidMount() {
    this.setState({ items: this.createItemComponents() })
  }

  createItemComponents() {
    return this.props.items.length !== 0
      ? this.props.items.map(item => <ItemComponent item={item} />);
      : <p>No items to show</p>;
  }

  render() {
   <SomeLoadingIndicator active={this.state.items.length === 0} />

   <div>{this.state.items}</div>
  }
}

Upvotes: 0

Yossi
Yossi

Reputation: 6027

Here is an idea:

  1. You pass a callback prop to ItemComponent
  2. This callback is called from ItemComponent's componentDidMount(),for initial render, and componentDidUpdate() for following renders.
  3. The callback increments a state variable in MyWrapper
  4. Loading... is displayed when this state variable equals length

Note that the state variable that counts renders should be updated using a function as a parameter, to make sure that it is incremented properly (see this)

Upvotes: 1

Tomas Eglinskas
Tomas Eglinskas

Reputation: 855

These are just my experiments how to do - I would suggest to take some ideas and try it out yourself, maybe it will get you on a right track or maybe this is baloney

https://codesandbox.io/s/k2mpvkr2n7

The main idea is to put the list in a separate component and change the loading state when it mounts.

For visual stuff I put a setTimeout and ignore the cow array (:

Upvotes: 1

Related Questions