Vanmeeganathan P K
Vanmeeganathan P K

Reputation: 211

Adding a day to React state Date object created using useState

I am having a state object in React which has a Date value.

const [myDate, setMyDate] = useState(new Date());

How do I increment the date by one day using setMyDate() ?

Upvotes: 0

Views: 1563

Answers (2)

Shashank Dubey
Shashank Dubey

Reputation: 353

You can use moment.js from npm.

setMyDate(moment(myDate).add(1, 'days').format());

Upvotes: 0

Idrizi.A
Idrizi.A

Reputation: 12010

You should return a different object in setMyDate so that React can tell it has been modified, try:

setMyDate(date => {
    date.setDate(date.getDate() + 1);
    return new Date(date)
});

Upvotes: 1

Related Questions