'How to call a function in React? Converting Jquery / Javascript to React functional component
I am in the process of converting my regular HTML, CSS and Javascript project into React but stuck halfway through the point in which I'm supposed to convert my Javascript / Jquery code into something that will work in my react functional component.
The project is a clock that highlights part of the HTML depending on what time it is using CSS.
I have a section where the main function from the Javascript file is written and have placed it in my functional component above my JSX. Beneath that is the HTML that I would like to return, see below:
import * as React from "react"
import $ from "jquery"
function Livestream() {
function updateClock() {
var d = new Date()
var nhour = d.getHours(),
nmin = d.getMinutes(),
nsec = d.getSeconds()
nhour = nhour > 12 ? nhour - 12 : nhour
// Removes old color class
$(".now").css("color", "").removeClass("now")
//Accessing classes from HTML
$(".hour-" + nhour).addClass("now")
//Accessing classes from HTML
$(".min-" + nmin).addClass("now")
$(".now").css("color", "rgba(255, 255, 0, 1)")
$(".second-hand").css({
width: (nsec / 60) * 100 + "%",
"background-color": "rgba(255, 255, 0, 1)",
})
}
return (
<div class="datetime">
<div class="clock-band">
<ul class="timeblock hours">
<li class="hour-12">12pm</li>
*** REPEATS UNTILL 9pm ***
<li class="hour-9">9pm</li>
</ul>
</div>
<div class="clock-band">
<ul class="timeblock minutes">
<li class="min-0">00</li>
<li class="min-1">01</li>
*** REPEATS UNTILL 59min ***
<li class="min-59">59</li>
</ul>
</div>
<div class="second-hand"></div>
<div class="date">
<div class="date-day">Tuesday</div>
<div class="calendarblock">
<div class="date-number">10th</div>
<div class="date-month">May</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Livestream
Everything renders correctly but the program does not update.
I essentially need a way to call the updateClock() function that is written into the component. I have basically just taken the Javascript function here and placed it within my react functional component in a way that allows compiling however I know this is not the best strategy in terms of utilising React's tools.
I'm just not really sure what direction is supposed to be taken from here.
What strategy shall I take to convert this in a way that will allow the program to run?
Thank you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
