Skip to content

Commit b7bfe5e

Browse files
authored
Replace unsafe method with getDerivedStateFromProps (#932)
1 parent 63f1845 commit b7bfe5e

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

src/components/radioButton/RadioGroup.tsx

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import _ from 'lodash';
2-
import React, {PureComponent} from 'react';
3-
import {asBaseComponent, forwardRef, BaseComponentInjectedProps, ForwardRefInjectedProps} from '../../commons/new';
2+
import React, {PureComponent, GetDerivedStateFromProps} from 'react';
3+
import {
4+
asBaseComponent,
5+
forwardRef,
6+
BaseComponentInjectedProps,
7+
ForwardRefInjectedProps
8+
} from '../../commons/new';
49
import View from '../view';
510
import RadioGroupContext from './RadioGroupContext';
611

@@ -19,7 +24,9 @@ interface RadioGroupState {
1924
value?: RadioGroupPropTypes['initialValue'];
2025
}
2126

22-
type Props = RadioGroupPropTypes & BaseComponentInjectedProps & ForwardRefInjectedProps;
27+
type Props = RadioGroupPropTypes &
28+
BaseComponentInjectedProps &
29+
ForwardRefInjectedProps;
2330

2431
/**
2532
* Wrap a group of Radio Buttons to automatically control their selection
@@ -35,10 +42,24 @@ class RadioGroup extends PureComponent<Props, RadioGroupState> {
3542
};
3643
}
3744

38-
UNSAFE_componentWillReceiveProps(nextProps: Props) {
39-
if (this.props.initialValue !== nextProps.initialValue) {
40-
this.setState({value: nextProps.initialValue});
45+
static getUpdatedState = (
46+
nextProps: Props,
47+
prevState: RadioGroupState
48+
): RadioGroupState | null => {
49+
const {value} = prevState;
50+
const {initialValue} = nextProps;
51+
52+
if (_.isUndefined(nextProps.initialValue) || value === initialValue) {
53+
return null;
4154
}
55+
56+
return {
57+
value: initialValue
58+
}
59+
};
60+
61+
static getDerivedStateFromProps: GetDerivedStateFromProps<Props, RadioGroupState> = (props, state) => {
62+
return RadioGroup.getUpdatedState(props, state);
4263
}
4364

4465
getContextProviderValue() {
@@ -62,4 +83,6 @@ class RadioGroup extends PureComponent<Props, RadioGroupState> {
6283
}
6384
}
6485

65-
export default asBaseComponent<RadioGroupPropTypes>(forwardRef(RadioGroup));
86+
export {RadioGroup}; // For tests
87+
88+
export default asBaseComponent(forwardRef(RadioGroup));

0 commit comments

Comments
 (0)