Search code examples
javascriptreactjstypescriptimagesettimeout

setTimeout with text AND <img src>? getting [object Object]


Im trying to set useState/timeout to display text and an icon image after 5 seconds, text is fine but i want to be able to also have an image:

import slackbot from '../../public/images/slackbot.png'

const [text, setText] = useState('')

useEffect(() => {
  const timeout = setTimeout(() => {
    setText( {slackbot} + 'this will be the slackbot auto message' )
  }, 3000)
}, [])

attempting to add it in the use State set Text as shown above but leaves me with an [object Object] display.


Solution

  • You likely don't need to add the image source to the state string (and in fact that won't work). Here's a potential solution: just store the text in state and conditionally show the text and image if that text is set.

    import slackbot from "../../public/images/slackbot.png";
    
    function Component() {
      const [text, setText] = useState("");
    
      useEffect(() => {
        const timeout = setTimeout(() => {
          setText("this will be the slackbot auto message");
        }, 3000);
      }, []);
    
      return (
        <div>
          {text && (
            <>
              <img src={slackbot} /> {text}
            </>
          )}
        </div>
      );
    }