Skip to content
Advertisement

Rendering a React component using ES generator

I have a very basic implementation of a sleep function which resolves a promise after x miliseconds:

module.exports = (ms) => new Promise(res => setTimeout(res, ms));

I then need to render a React component in an ES6 Stateful Class Component after the sleep, but this sadly throws the error: Objects are not valid as a React child. Is there something wrong with this generator implementation?

import sleep from './sleep';
class Dummy extends React.Component {

  *renderSubComponent(arg) {
    yield sleep(1000);
    return (<ChildComponent {...arg} />);
  }

  render() {
    return (
     {this.props.check ? this.renderSubComponent(this.props.check).next() : null}
    );
  }

}

I can not use async/await.

Advertisement

Answer

Basically, you can’t make this implementation because the generator returns an iterator and if don’t program the iteration then nothing will happen.

A more reasonable solution for this will be using the component’s state so you can keep the state in the same component and then you can mutate it

This is how the component will look like

class Dummy extends React.Component {
  constructor(props) {
    super(props);

    this.setState({
      renderSubComponent: false,
    });
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        renderSubComponent: true,
      });
    }, 1000);
  }

  render() {
    const { renderSubComponent } = this.state;
    let subComponent;

    if(renderSubComponent) subComponent = (<ChildComponent check={this.props.check} />);

    return (
      <div>
        {subComponent}
      </div>
    );
  }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement