0

I have created a timeout function for 3 seconds and after that time it is supposed to render the HTML. I'm following the official documentation to do this and the code is like on the documentation. Anyone has had a similar issue?

render() {
return (
<div>
    {this.state.activePage === 'Home' ? setTimeout(function () {
        <p>Hello World</p>
    }, 3000) : null}
</div>
)
}
  • Don't do this in the render. Instead use a `useEffect`, or put it in the constructor, and change state. – evolutionxbox Jan 14 '22 at 14:20
  • Can you provide a link to where you are seeing this in the documentation? Was was not under the impression you could execute asynchronous code inside of JSX in this manner.... – Alexander Nied Jan 14 '22 at 14:21
  • [This approach uses react native](https://stackoverflow.com/questions/34504322/settimeout-in-react-native), but it's pretty much the same thing – evolutionxbox Jan 14 '22 at 14:22

2 Answers2

1

You should not write code like that in react. The setTimeout returns:

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(). T

and not the JSX which you returned from callback. But even if it did asynchronously return the JSX which you return from callback, you won't see the new content on the screen. To change UI in react you must change a state variable using setState which will cause a re render. Also render is not the place to call setState. You can call setState in useEffect for example.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

It is not possible to return a value from the function passed to setTimeout.

Here are two options you could try

  1. Create a state field to store the message you want to display and update the state from inside of the setTimeout. Also such an update cannot be done inside of the return. You would want to move this logic to a component mount function.
  2. Here is a more vanilla JS approach to this issue using promise objects Get return value from setTimeout

Also could you provide the document you are referring to for this code, so we can have a deeper dive onto the issue?

Mahesh
  • 1