-
-
Notifications
You must be signed in to change notification settings - Fork 32.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Radio] Support uncontrolled mode #13915
Comments
@Slessi The radio component needs to be controlled somewhere. React only trigger a change event on the radio that receives the new value, nothing happens on the already selected radio. This means that we can't keep track of the selection state individually for each radio, the logic has to be centralized in the radio group component: facebook/react#1471. What's your use case for an uncontrolled radio group? |
I'm lazy and didn't feel like writing |
@Slessi Ok, this sounds valid to me. I think that we should implement an uncontrolled logic in the radio group. Do you want to give it a shot? |
@Slessi What do you think of this change? --- a/packages/material-ui/src/RadioGroup/RadioGroup.js
+++ b/packages/material-ui/src/RadioGroup/RadioGroup.js
@@ -9,6 +9,15 @@ import { createChainedFunction, find } from '../utils/helpers';
class RadioGroup extends React.Component {
radios = [];
+ state = {
+ value: null,
+ };
+
+ constructor(props) {
+ super(props);
+ this.isControlled = props.value != null;
+ }
+
focus = () => {
if (!this.radios || !this.radios.length) {
return;
@@ -30,15 +39,22 @@ class RadioGroup extends React.Component {
focusRadios[0].focus();
};
- handleRadioChange = (event, checked) => {
- if (checked && this.props.onChange) {
+ handleChange = event => {
+ if (!this.isControlled) {
+ this.setState({
+ value: event.target.value,
+ });
+ }
+
+ if (this.props.onChange) {
this.props.onChange(event, event.target.value);
}
};
render() {
- const { children, name, value, onChange, ...other } = this.props;
+ const { children, name, value: valueProp, onChange, ...other } = this.props;
+ const value = this.isControlled ? valueProp : this.state.value;
this.radios = [];
return (
@@ -64,7 +80,7 @@ class RadioGroup extends React.Component {
}
},
checked: value === child.props.value,
- onChange: createChainedFunction(child.props.onChange, this.handleRadioChange),
+ onChange: createChainedFunction(child.props.onChange, this.handleChange),
});
})}
</FormGroup> |
Looks ok to me - Not sure if Might want to implement that warning the other inputs have too
|
@Slessi This warning should already be triggered:
Alright, great. Let's leave it here and wait for somebody to submit a pull request :). |
Expected Behavior 🤔
Clicking radio button should select it
Current Behavior 😯
Clicking radio button does not select it
Steps to Reproduce 🕹
Link: https://codesandbox.io/s/2pw922z7xn
Context 🔦
I want an uncontrolled Radio group
Your Environment 🌎
The text was updated successfully, but these errors were encountered: