Nagireddy Hanisha
Nagireddy Hanisha

Reputation: 1440

Rendering a new component inside componentDidMount - React

I will have to render a new component after all the expected components are loaded. I will need a timeout based on which the the new component has to be rendered. So this new component has to show up after 5 minutes after the page has loaded. I need to render a component called new_component that extends React.component

public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }

Can someone help me call the render function of new_component inside componentDidMount please. i tried new_component.render(). But that does not seem to work.

Upvotes: 0

Views: 563

Answers (3)

Max
Max

Reputation: 2036

You can go with this code, wait and then render new one:

cosnt FIVE_MIN = 5 * 60 * 1000

class Example {
  this.state = { isShowComponent: false }
  timer 

  componentDidMount() {
    this.timer = setTimeout(() => {
      this.setState({ isShowComponent: true })
    }, FIVE_MIN) 
  }

  componentWilllUnmount() {
    clearTimeout(this.timer)
  }

  render() {
    if (this.state.isShowComponent) return <NewComponent />
    
    return <Component />
  }
}

Upvotes: 0

gnujoow
gnujoow

Reputation: 374

you can render your component by your state.

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isTimeout: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    this.checkTimeout = setTimeout(() => { 
      this.setState(() => ({isTimeout: true}))
    }, 500);
  }
  componentWillUnmount() {
    // clean it up when the component is unmounted.
    clearTimeout(this.checkTimeout);
  }
  render () {
    if (isTimeout) {
        return (k<h1>time is running out</h1>)
    }

    return (<h1>hello world.</h1>)
  }
}

Upvotes: 0

thedude
thedude

Reputation: 9812

You can use state to track this.

componentDidMount() {
    setTimeout(() => {
        this.setState({ showNewComponent: true })
    })
}

and in render:

render() {
    if (this.state.showNewComponent) {
         return <NewComponent />
    }
    return null
}

Upvotes: 3

Related Questions