Skip to content
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

[RadioGroup] Remove cloneElement, use the context #15069

Merged
merged 2 commits into from
Mar 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions packages/material-ui/src/Radio/Radio.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import clsx from 'clsx';
import SwitchBase from '../internal/SwitchBase';
import RadioButtonUncheckedIcon from '../internal/svg-icons/RadioButtonUnchecked';
import RadioButtonCheckedIcon from '../internal/svg-icons/RadioButtonChecked';
import { capitalize } from '../utils/helpers';
import { capitalize, createChainedFunction } from '../utils/helpers';
import withStyles from '../styles/withStyles';
import RadioGroupContext from '../RadioGroup/RadioGroupContext';

export const styles = theme => ({
/* Styles applied to the root element. */
Expand Down Expand Up @@ -37,7 +38,28 @@ export const styles = theme => ({
});

const Radio = React.forwardRef(function Radio(props, ref) {
const { classes, color, ...other } = props;
const {
checked: checkedProp,
classes,
color,
name: nameProp,
onChange: onChangeProp,
...other
} = props;
const radioGroup = React.useContext(RadioGroupContext);

let checked = checkedProp;
const onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange);
let name = nameProp;

if (radioGroup) {
if (typeof checked === 'undefined') {
checked = radioGroup.value === props.value;
}
if (typeof name === 'undefined') {
name = radioGroup.name;
}
}

return (
<SwitchBase
Expand All @@ -49,6 +71,9 @@ const Radio = React.forwardRef(function Radio(props, ref) {
checked: classes.checked,
disabled: classes.disabled,
}}
name={name}
checked={checked}
onChange={onChange}
ref={ref}
{...other}
/>
Expand Down Expand Up @@ -97,6 +122,10 @@ Radio.propTypes = {
* Use that property to pass a ref callback to the native input component.
*/
inputRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* Callback fired when the state is changed.
*
Expand Down
15 changes: 1 addition & 14 deletions packages/material-ui/src/Radio/Radio.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,14 @@ import React from 'react';
import { assert } from 'chai';
import RadioButtonCheckedIcon from '../internal/svg-icons/RadioButtonChecked';
import RadioButtonUncheckedIcon from '../internal/svg-icons/RadioButtonUnchecked';
import {
getClasses,
createShallow,
createMount,
describeConformance,
} from '@material-ui/core/test-utils';
import SwitchBase from '../internal/SwitchBase';
import { getClasses, createMount, describeConformance } from '@material-ui/core/test-utils';
import Radio from './Radio';

describe('<Radio />', () => {
let shallow;
let classes;
let mount;

before(() => {
shallow = createShallow({ dive: true });
classes = getClasses(<Radio />);
mount = createMount();
});
Expand All @@ -42,11 +34,6 @@ describe('<Radio />', () => {
});
});

it('should be using SwitchBase', () => {
const wrapper = shallow(<Radio />);
assert.strictEqual(wrapper.type(), SwitchBase);
});

describe('prop: unchecked', () => {
it('should render an unchecked icon', () => {
const wrapper = mount(<Radio />);
Expand Down
65 changes: 20 additions & 45 deletions packages/material-ui/src/RadioGroup/RadioGroup.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,31 @@ import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import FormGroup from '../FormGroup';
import { createChainedFunction, find } from '../utils/helpers';
import { setRef } from '../utils/reactHelpers';
import RadioGroupContext from './RadioGroupContext';

const RadioGroup = React.forwardRef(function RadioGroup(props, ref) {
const { actions, children, defaultValue, name, value: valueProp, onChange, ...other } = props;
const radiosRef = React.useRef([]);
const { actions, children, name, value: valueProp, onChange, ...other } = props;
const rootRef = React.useRef();
const { current: isControlled } = React.useRef(props.value != null);
const [valueState, setValue] = React.useState(() => {
if (!isControlled) {
return defaultValue;
return props.defaultValue;
}
return null;
});

React.useImperativeHandle(actions, () => ({
focus: () => {
const radios = radiosRef.current;
if (!radios.length) {
return;
}

const focusRadios = radios.filter(n => !n.disabled);
let input = rootRef.current.querySelector('input:not(:disabled):checked');

if (!focusRadios.length) {
return;
if (!input) {
input = rootRef.current.querySelector('input:not(:disabled)');
}

const selectedRadio = find(focusRadios, n => n.checked);

if (selectedRadio) {
selectedRadio.focus();
return;
if (input) {
input.focus();
}

focusRadios[0].focus();
},
}));

Expand Down Expand Up @@ -67,34 +58,18 @@ const RadioGroup = React.forwardRef(function RadioGroup(props, ref) {
onChange(event, event.target.value);
}
};
const context = { name, onChange: handleChange, value };

radiosRef.current = [];
return (
<FormGroup role="radiogroup" ref={ref} defaultValue={defaultValue} {...other}>
{React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return null;
}

warning(
child.type !== React.Fragment,
[
"Material-UI: the RadioGroup component doesn't accept a Fragment as a child.",
'Consider providing an array instead.',
].join('\n'),
);

return React.cloneElement(child, {
name,
inputRef: node => {
if (node) {
radiosRef.current.push(node);
}
},
checked: value === child.props.value,
onChange: createChainedFunction(child.props.onChange, handleChange),
});
})}
<FormGroup
role="radiogroup"
ref={nodeRef => {
setRef(ref, nodeRef);
setRef(rootRef, nodeRef);
}}
{...other}
>
<RadioGroupContext.Provider value={context}>{children}</RadioGroupContext.Provider>
</FormGroup>
);
});
Expand Down
26 changes: 6 additions & 20 deletions packages/material-ui/src/RadioGroup/RadioGroup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,49 +117,35 @@ describe('<RadioGroup />', () => {

it('should focus the selected radio', () => {
const actionsRef = React.createRef();
const zeroRadioOnFocus = spy();
const oneRadioOnFocus = spy();
const twoRadioOnFocus = spy();
const threeRadioOnFocus = spy();

mount(
<RadioGroup actions={actionsRef} value="two">
<Radio value="zero" disabled onFocus={zeroRadioOnFocus} />
<Radio value="one" onFocus={oneRadioOnFocus} />
<Radio value="zero" disabled />
<Radio value="one" />
<Radio value="two" onFocus={twoRadioOnFocus} />
<Radio value="three" onFocus={threeRadioOnFocus} />
<Radio value="three" />
</RadioGroup>,
);

actionsRef.current.focus();

assert.strictEqual(zeroRadioOnFocus.callCount, 0);
assert.strictEqual(oneRadioOnFocus.callCount, 0);
assert.strictEqual(twoRadioOnFocus.callCount, 1);
assert.strictEqual(threeRadioOnFocus.callCount, 0);
});

it('should focus the non-disabled radio rather than the disabled selected radio', () => {
const actionsRef = React.createRef();
const zeroRadioOnFocus = spy();
const oneRadioOnFocus = spy();
const twoRadioOnFocus = spy();
const threeRadioOnFocus = spy();

mount(
<RadioGroup actions={actionsRef} value="two">
<Radio value="zero" disabled onFocus={zeroRadioOnFocus} />
<Radio value="one" disabled onFocus={oneRadioOnFocus} />
<Radio value="two" disabled onFocus={twoRadioOnFocus} />
<Radio value="zero" disabled />
<Radio value="one" disabled />
<Radio value="two" disabled />
<Radio value="three" onFocus={threeRadioOnFocus} />
</RadioGroup>,
);

actionsRef.current.focus();

assert.strictEqual(zeroRadioOnFocus.callCount, 0);
assert.strictEqual(oneRadioOnFocus.callCount, 0);
assert.strictEqual(twoRadioOnFocus.callCount, 0);
assert.strictEqual(threeRadioOnFocus.callCount, 1);
});

Expand Down
8 changes: 8 additions & 0 deletions packages/material-ui/src/RadioGroup/RadioGroupContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';

/**
* @ignore - internal component.
*/
const RadioGroupContext = React.createContext();

export default RadioGroupContext;
5 changes: 0 additions & 5 deletions packages/material-ui/src/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ export function findIndex(arr, pred) {
return -1;
}

export function find(arr, pred) {
const index = findIndex(arr, pred);
return index > -1 ? arr[index] : undefined;
}

/**
* Safe chained function
*
Expand Down
12 changes: 1 addition & 11 deletions packages/material-ui/src/utils/helpers.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { assert } from 'chai';
import { capitalize, contains, find } from './helpers';
import { capitalize, contains } from './helpers';

describe('utils/helpers.js', () => {
describe('capitalize', () => {
Expand All @@ -14,16 +14,6 @@ describe('utils/helpers.js', () => {
});
});

describe('find(arr, pred)', () => {
it('should search for an item in an array containing the predicate', () => {
const array = ['woofHelpers', 'meow', { foo: 'bar' }, { woofHelpers: 'meow' }];
assert.strictEqual(find(array, 'lol'), undefined);
assert.strictEqual(find(array, 'woofHelpers'), array[0]);
assert.strictEqual(find(array, { foo: 'bar' }), array[2]);
assert.strictEqual(find(array, n => n && n.woofHelpers === 'meow'), array[3]);
});
});

describe('contains(obj, pred)', () => {
it('should check if an object contains the partial object', () => {
const obj = { woofHelpers: 'meow', cat: 'dog' };
Expand Down
1 change: 1 addition & 0 deletions pages/api/radio.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import Radio from '@material-ui/core/Radio';
| <span class="prop-name">id</span> | <span class="prop-type">string</span> |   | The id of the `input` element. |
| <span class="prop-name">inputProps</span> | <span class="prop-type">object</span> |   | Attributes applied to the `input` element. |
| <span class="prop-name">inputRef</span> | <span class="prop-type">union:&nbsp;func&nbsp;&#124;<br>&nbsp;object<br></span> |   | Use that property to pass a ref callback to the native input component. |
| <span class="prop-name">name</span> | <span class="prop-type">string</span> |   | Name attribute of the `input` element. |
| <span class="prop-name">onChange</span> | <span class="prop-type">func</span> |   | Callback fired when the state is changed.<br><br>**Signature:**<br>`function(event: object, checked: boolean) => void`<br>*event:* The event source of the callback. You can pull out the new value by accessing `event.target.value`.<br>*checked:* The `checked` value of the switch |
| <span class="prop-name">type</span> | <span class="prop-type">string</span> |   | The input component property `type`. |
| <span class="prop-name">value</span> | <span class="prop-type">union:&nbsp;string&nbsp;&#124;<br>&nbsp;number&nbsp;&#124;<br>&nbsp;bool<br></span> |   | The value of the component. |
Expand Down