Reputation: 4882
I have below composition:
const HookComponent = (props)=> {
let [month, changeMonth] = useState(moment());
return (
<ChildComponent
month={month}
onChange={m => changeMonth(m)}
minStep={5}
prevMonthIcon="ion-ios-arrow-left"
nextMonthIcon="ion-ios-arrow-right"
/>
)
}
The ChildComponent is a class component which updates the month using setState. Problem with above is that the change is not reflecting on DOM but the state in parent component is changing (via user input - button which changes the state in ChildComponent). I logged it and confirm the month in parent is changing. Is this some limitation of react when using class components within hooks?
When I convert HookComponent to class component and change month using setState, it works as expected and DOM changes on input change.
Upvotes: 0
Views: 344
Reputation: 6325
It seems that the InputMoment
component does not use a month
prop, but a moment
one.
Also, it seems that InputMoment
is returning the same moment instance that is passed as moment
prop. This causes that when you execute the changeMonth
statement, as the reference does not change, the element is not re-rendered.
You can solve this by storing an object in the state. When you call changeMonth
you pass a new object, and the InputMoment
is then re-rendered correctly:
const HookComponent = (props)=> {
let [month, changeMonth] = useState({ m: moment() });
return (
<ChildComponent
moment={month.m}
onChange={m => changeMonth({ m })}
minStep={5}
prevMonthIcon="ion-ios-arrow-left"
nextMonthIcon="ion-ios-arrow-right"
/>
)
}
Upvotes: 0