i try to learn React JS and i don't understand how is functionning the "main function', i did a timer who gives me the date and the hour but it actualize the timer only when i write something on my searchbox.
There is my code:
return (
<div className="app">
<main>
<div className="search-box">
<input
type="text"
className="search-bar"
placeholder="Search..."
onChange={e =>setQuery(e.target.value)}
value = {query}
onKeyPress={search}
/>
</div>
<div className="location">
{weather.temp}
</div>
<div className="location">
{new Date().toLocaleString() + ''}
</div>
</main>
<div>
</div>
</div>
);
}
export default App;
it only actualize the date when i press my keys in my form. I'm totally new in JS so i think i missunderstand something.
Thanks for your answers!
You need to use one of the timer functions supplied by the JavaScript host environment, such as setInterval or setTimeout.
The following code configures a React component Clock that updates itself every second using a setInterval timer.
const { useState, useEffect } = React
const Clock = (props) => {
const {initialHours = '--', initialMinutes = '--', initialSeconds = '--', initialTimezoneOffset = ''} = props;
const [hours, setHours] = useState(initialHours);
const [minutes, setMinutes] = useState(initialMinutes);
const [seconds, setSeconds] = useState(initialSeconds);
const [timezoneOffset, setTimezoneOffset] = useState(initialTimezoneOffset);
useEffect(()=>{
const intervalId = setInterval(() => {
const now = new Date
const timezoneOffset = -now.getTimezoneOffset()/60
setHours(now.getHours())
setMinutes(String(now.getMinutes()).padStart(2, '0'))
setSeconds(String(now.getSeconds()).padStart(2, '0'))
setTimezoneOffset(`${timezoneOffset >= 0 ? '+' : '-'}${timezoneOffset}`)
}, 1000)
return ()=> {
clearInterval(intervalId)
}
})
return (
<div>{hours}:{minutes}:{seconds} UTC{timezoneOffset}</div>
)
}
ReactDOM.render(
<Clock/>,
document.querySelector('main')
)
* {
font-family: Courier;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<main></main>
I think part of your code is missing here, anyway, if you are new I recommend you to stick to hooks. useState https://reactjs.org/docs/hooks-state.html and useEffect https://reactjs.org/docs/hooks-effect.html is probably what you are looking for.