Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Right way to modify a property in a state object?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

          <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

Thanks a lot

>Solution :

All seams fine to me, except setting state:

  const handleFocusChange = item => {
    setCalendarConfig((prevConfig) => {
      prevConfig.focusedRange = item;
      return prevConfig;
    });
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading