Question:
I’m making a countdown and I want that the user can say to which date the countdown should go. I already created an input from the user and I guess I should change the const difference to use the date from the input but I don’t know how I could do that.Answer:
As I mentioned on my comment, every input has aonChange
prop in which you can get updates when the value changes.So you can create a new state variable that will hold the target date, and call its setter when that event happens:
value={formatDate(date)}
on the input is not always needed, but on yours it is, because you want to show the initial date which is a specific one – Check for “Controlled vs uncontrolled components”- I had to format the date into a yyyy-mm-dd string because it’s what the
input type="date"
requires for its value. But your state is of typeDate
, we just format it when we’re about to pass it to the input. - There’s a different way of handling this altogether.
timeLeft
is in essence a derived state ofdate
, but you need to rerender the component every second. You could then avoid having a state fortimeLeft
, and just calculate it whenever the component renders. And have something that forces a rerender every second. It’s a bit more advanced and there are devs that don’t really like this method, so don’t worry too much about it.
Hope that helps!
If you have better answer, please add a comment about this, thank you!