0

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

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Agustin G.
  • 72
  • 3
  • 19
  • Your approach is correct, although nested state is not best practice ([why](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react#51136076)). Why it is failing I cant see right now, but it's probably not directly related to `onRangeFocusChange={item => handleFocusedRange(item)}` – Tea_Lover_418 May 31 '22 at 15:25
  • maybe it's `handleFocusedRange` and `handleFocusChange` diff names problem? – I-vasilich-I May 31 '22 at 15:27

1 Answers1

2

All seams fine to me, except setting state:

  const handleFocusChange = item => {
    setCalendarConfig((prevConfig) => {
      prevConfig.focusedRange = item;
      return prevConfig;
    });
  };
I-vasilich-I
  • 258
  • 1
  • 8
  • YES! this is the right way, sorry, could you explain to me, or give some link to read, in order to know what are you doing here? – Agustin G. May 31 '22 at 15:31
  • 1
    @AgustinG. Read part about functional updates https://reactjs.org/docs/hooks-reference.html#usestate – I-vasilich-I May 31 '22 at 15:34