Arsene Wenger
Arsene Wenger

Reputation: 659

Render a react component after specific time interval

I have the following line of code. Without setTimeout, things working properly. When I enable, setTimeout, there is no output.

What I am doing wrong?

const PrintBox = ({posts,maximise,data}) => {
 if ((posts)&& posts.postType === "printplease"
 {
   setTimeout( function () { 
      return (
         <div>
           <h1>PrintPlease <h1>
         </div>
      )
   }, 6000);
 }   
}

Real world code looks very similar to this. The timing of each post depends on the current post (it changes for every post..)

const PrintBox = ({posts, maximise}) => {

if ((posts)&& posts.postType === "printplease") {
      setTimeout(function(){ 
       return ( <div>
             {(maximise === false)?
             (
              <div className="outerbox">
               <div>
                 <div className="container">
                   <Printbox
                     data ={data}
                     maximise ={maximise}
                   />
                </div>
               </div>
              </div>
             ) : (
             <div 
              className="outerbox outexpand">
              <div className= "container container-extend"
             >
               <Printbox
                 data ={data}
                 maximise ={maximise}
               />
            </div>
         </div>
       )}
     </div>
   </div>
   },post.timing);
}


Upvotes: 1

Views: 2859

Answers (2)

zain ul din
zain ul din

Reputation: 619

You can use the boolean flag to achieve this. have a look at this code

import React ,{useState , useEffect} from 'react'

export default const Component = () =>{
  const [canShow , setCanShow] = useState(false)
  
  // Set Time out
  useEffect(()=>{
    const timer = setTimeout( () => setCanShow(true) , 1000)
    return () => clearTimeout(timer);
  }, [])
  
  return (
    {canShow ? <h1> visible </h1> : <> </>}
  )
}

Upvotes: 7

Fiston Emmanuel
Fiston Emmanuel

Reputation: 4849

Due to how React works internally, It's recommended to use hook optimized for React render cycles.

import { useEffect, useRef, useState } from "react";

function useTimeout(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      const id = setTimeout(tick, delay);
      return () => clearTimeout(id);
    }
  }, [delay]);
}

export default function App() {
  const [isIdle, setIdle] = useState(true);

  useTimeout(() => setIdle(false), 1000 * 3);
  return <div>{isIdle ? "Waiting..." : "Ready to print"}</div>;
}


Demo preview - https://codesandbox.io/s/xenodochial-wildflower-6r9e5g?file=/src/App.js:0-663

Upvotes: 4

Related Questions