skip to Main Content

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.

2

Answers


  1. 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>
      );
    }
    
    Login or Signup to reply.
  2. First of all The useState and useEffect hooks are designed to be used within a React functional component. They are part of the React Hooks API and rely on the component’s lifecycle to work correctly.

    If you try to use these hooks outside of a functional component, such as in the global scope or in a regular JavaScript function, you will encounter an error. React hooks can only be used within the body of a functional component or within custom hooks.

    To fix this, make sure you are using the useState and useEffect hooks inside a React functional component. If you need to perform certain actions outside of a component, you can create a custom hook and call it from within your functional components.

    Secondly, in your code, there is an issue with the way you are concatenating the slackbot image variable with the text string. Instead of concatenating the image variable correctly, you are wrapping it inside curly braces ({slackbot}), which will result in an object representation of the image.

    To fix the issue, you need to update the concatenation in the setText function call.
    So just do this in your set state function:

    setText( slackbot + 'this will be the slackbot auto message' )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search