Home > Mobile >  Right way to modify a property in a state object?
Right way to modify a property in a state object?

Time:06-01

I'm working with react 17.0.2 and next 12.0.0, and use react-date-range (https://www.npmjs.com/package/react-date-range)

I have this 3 states

const [calendarDates, setCalendarDates] = useState(null);
const [wasCleared, setWasCleared] = useState(true);
const [focusedRange, setFocusedRange] = useState([0, 0]);

Then, when i call the component:

          <DateRangePicker
            preventSnapRefocus
            showPreview
            showSelectionPreview
            direction="horizontal"
            focusedRange={focusedRange}
            minDate={new Date()}
            monthDisplayFormat="MMMM yyyy"
            months={2}
            ranges={calendarConfig.calendarDates}
            showDateDisplay={false}
            showMonthAndYearPickers={false}
            weekdayDisplayFormat="EEEEEE"
            onChange={item => handleDatesChange([item.selection])}
            onRangeFocusChange={setFocusedRange} // this is the line what i dont understand
          />

I want to change these 3 states for just one, that has in the 3 properties, just like:

const [calendarConfig, setCalendarConfig] = useState({
  focusedRange: [0, 0],
  wasCleared: true,
  calendarDates: null
});

Now, i want to change this line

onRangeFocusChange={setFocusedRange}

for this

onRangeFocusChange={item => handleFocusedRange(item)}

Then, i do:

const handleFocusChange = item => {
    setCalendarConfig({
      ...calendarConfig,
      focusedRange: item,
    });
  };

but doesn't work.

My question is, what are exactly doing this? onRangeFocusChange={setFocusedRange} and how i can replace it, in order to change calendarConfig.focusedRange

CodePudding user response:

All seams fine to me, except setting state:

  const handleFocusChange = item => {
    setCalendarConfig((prevConfig) => {
      prevConfig.focusedRange = item;
      return prevConfig;
    });
  };
  • Related