Skip to main content

updating state object property - date, based on previous value

I want to increment date with each button click (next day each click). How to update object state property and increment date value, properly???

const {useState} = React;

const DateComponent = () => {
  const [date, setDate] = useState({
    currDate: new Date().toLocaleDateString(),
    active: true
  });

  const nextDate = () => {
    setDate({
      ...date,
      currDate: date.currDate.setDate(date.currDate.getDate() + 1)
    });
  };

  return (
    <div>
      <span>{date.currDate}</span>
      <button onClick={nextDate}>Next Day</button>
    </div>
  );
}




ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <DateComponent />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
Via Active questions tagged javascript - Stack Overflow https://ift.tt/GZxKLEV

Comments