Antonio contreras
Antonio contreras

Reputation: 137

How to enable button to be clicked for current and previous days but not for future ones?

I am currently trying to have buttons that change the completion of a ToDo when clicked, but I only want to enable the button to be clicked for previous days and the current one.

For example, let's say that it is Wednesday, then I want my button to be enabled for Monday, Tuesday and Wednesday, but not for later days.

In my API I couldn't get the Days to be sent, just the id of the Day. So Sun: 1 ... Sat:7, and I can't think of a way to do that.

This is a code snippet for today being Sunday so the button should be enabled, but it is disabled for the rest of the days, it is just an idea of what I am trying to accomplish.

<div key={day.id}>
  {habit.id === day.habitId && (
    <>
      {firstDay === "Sun" && day.id === 1 ?
        <form onSubmit={onSubmit}>
          {!day.isCompleted ? 
            <button type="submit" onClick={() => {setHandleChange([day.id, day.isCompleted]); setCompletion(!day.isCompleted)}}>[]</button>
            : <button style={{ color: habit.color }} type="submit" onClick={() => setHandleChange([day.id, day.isCompleted])}>[]</button>
          }
        </form>
        : <button disabled type="submit" onClick={(e) => {  setHandleChange([day.id, day.isCompleted]); setCompletion(e.target.value) }}>[]</button>
      }
    </>
  )}
</div>

firstDay is obtained by manipulating new Date so it is a dynamic variable. How can I make this idea dynamic, so that if the day.id === 7 then all the buttons can be clicked, if day.id === 1 then only the one for Sun can be clicked, if day.id === 3 then Sun, Mon and Tue can be clicked but not the rest?

Upvotes: 0

Views: 86

Answers (1)

Andy
Andy

Reputation: 63550

You could keep an array of day names, and then use getDay to get the index of "today". Then iterate over the days array, and if the current map index is greater than index of "today" disable the button.

function Example() {

  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const today = new Date().getDay();

  function handleClick(e) {
    const { dataset: { day } } = e.target;
    console.log(day);
  }

  function isDisabled(i) {
    return i > today;
  }

  return (
    <div>
      {days.map((day, i) => {
        return (
          <button
            data-day={day}
            type="button"
            onClick={handleClick}
            disabled={isDisabled(i)}
          >{day}
          </button>
        )
      })}
    </div>
  );

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Upvotes: 1

Related Questions