skip to Main Content

For React JS
I need to show a text in

after 2 seconds, it’s work in console but not in the DOM

  const items = document.getElementById("items");

  const errorDisplay = () => {
    setTimeout(function () {
      items.innerHTML = "please wait..";
      console.log(items);
    }, 2000);
  };

  <p id="items">  </p>

Thanks

  const items = document.getElementById("items");

  const errorDisplay = () => {
    setTimeout(function () {
      items.innerHTML = "please wait..";
      console.log(items);
    }, 2000);
  };

 <p id="items"> </p>

3

Answers


  1. Minimal example of React app with setState for controlling the visibility of the wait text, and useEffect to use the setTimeout function:

    HTML:

    <div id="root"></div>
    

    JavaScript:

    const root = ReactDOM.createRoot(document.getElementById("root"));
    
    function App() {
      const [showWait, setShowWait] = React.useState(false);
    
      React.useEffect(() => {
        const timer = setTimeout(() => {
          setShowWait(true);
          console.log("please wait ...");
        }, 3000);
        return () => clearTimeout(timer);
      }, []);
    
      return showWait && <p>please wait...</p>;
    }
    
    root.render(<App></App>);
    

    See https://codepen.io/michaeljoh/pen/RweVBpJ

    Login or Signup to reply.
  2. If you want to show a please wait paragraph for two seconds before displaying the products you can do something like this:

    import { useEffect, useState } from "react";
    
    const items = [{ id: 1 }, { id: 2 }];
    
    export default function App() {
    const [isWaiting, setIsWaiting] = useState(true);
    
    const productsListItems = items.map((item) => <li>{item.id}</li>);
    
    useEffect(() => {
    const timer = setTimeout(() => {
      setIsWaiting(false);
    
      return () => clearTimeout(timer);
     }, [2000]);
    }, []);
    
    return (
    <div className="App">
      {isWaiting && <p>Please wait...</p>}
      {!isWaiting && <ul>{productsListItems}</ul>}
    </div>
     );
    }
    
    Login or Signup to reply.
  3. Or refactor the returning jsx to this depending on your readability preferences:

    import { useEffect, useState } from "react";
    
    const items = [{ id: 1 }, { id: 2 }];
    
    export default function App() {
    const [isWaiting, setIsWaiting] = useState(true);
    
    const productsListItems = items.map((item) => <li>{item.id}</li>);
    
    const output = isWaiting ? <p>Please wait...</p> : <ul>{productsListItems}</ul>
    
    useEffect(() => {
    const timer = setTimeout(() => {
      setIsWaiting(false);
    
      return () => clearTimeout(timer);
     }, [2000]);
    }, []);
    
    return <div className="App">{output}</div>;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search