That won’t work because the setInterval
does not behave properly to the model that React works with.
In JSX, everything put between keys ({}
) is evaluated as an expression by React and rendered in the document. As setTimeout
, in the browsers, always returns a number (the ID of the timeout), it is he who will be rendered. Thus, put the JSX code inside the setTimeout
is wrong and of nothingness will help, since they are incompatible Apis for direct use.
To make it work the way the question example shows, setTimeout
would have to at least fit React’s "Suspense" model.
As primitive of the web, the setInterval
will never fit this model. They are different technologies that were not designed to work together without a handling additional.
It is about this "handling" that we will deal with next.
To make a component only render after a certain time, you must create a state variable to "know" when the component must be hidden or visible. You should also use the useEffect
to "integrate" with the setTimeout
.
A trivial example would be this:
function App() {
// Inicializamos um booleano no estado do componente para sabermos quando
// devemos mostrar ou esconder o componente de acordo com o `setTimeout`.
const [finishedTimeout, setFinishedTimeout] = React.useState(false);
// O "manejo" necessário: integraremos o `setTimeout` com o React através do
// hook `useEffect`:
React.useEffect(() => {
const id = setTimeout(() => {
setFinishedTimeout(true);
}, 1000);
return () => clearTimeout(id);
}, []);
return (
<div>
<h1>Sempre visível.</h1>
{finishedTimeout && <h1>Visível apenas 1s depois.</h1>}
</div>
);
}
ReactDOM.render(<App />, document.querySelector('#root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
It is important to understand the functioning of React Hooks.