Skip to content

Commit

Permalink
[SwitchBase] Add useControlled
Browse files Browse the repository at this point in the history
  • Loading branch information
m4theushw committed Jan 8, 2020
1 parent 7ba2cf3 commit 84ac74f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
13 changes: 7 additions & 6 deletions packages/material-ui/src/internal/SwitchBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import { useControlled } from '@material-ui/core/utils';
import useFormControl from '../FormControl/useFormControl';
import withStyles from '../styles/withStyles';
import IconButton from '../IconButton';
Expand Down Expand Up @@ -53,9 +54,11 @@ const SwitchBase = React.forwardRef(function SwitchBase(props, ref) {
value,
...other
} = props;
const { current: isControlled } = React.useRef(checkedProp != null);
const [checkedState, setCheckedState] = React.useState(Boolean(defaultChecked));
const checked = isControlled ? checkedProp : checkedState;
const [checked, setCheckedState] = useControlled({
controlled: checkedProp,
default: Boolean(defaultChecked),
name: 'SwitchBase',
});

const muiFormControl = useFormControl();

Expand All @@ -82,9 +85,7 @@ const SwitchBase = React.forwardRef(function SwitchBase(props, ref) {
const handleInputChange = event => {
const newChecked = event.target.checked;

if (!isControlled) {
setCheckedState(newChecked);
}
setCheckedState(newChecked);

if (onChange) {
onChange(event, newChecked);
Expand Down
10 changes: 8 additions & 2 deletions packages/material-ui/src/internal/SwitchBase.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -369,10 +369,13 @@ describe('<SwitchBase />', () => {
expect(consoleErrorMock.callCount()).to.equal(0);

wrapper.setProps({ checked: true });
expect(consoleErrorMock.callCount()).to.equal(1);
expect(consoleErrorMock.callCount()).to.equal(2);
expect(consoleErrorMock.args()[0][0]).to.include(
'A component is changing an uncontrolled input of type %s to be controlled.',
);
expect(consoleErrorMock.args()[1][0]).to.include(
'A component is changing an uncontrolled SwitchBase to be controlled.',
);
}),
);

Expand All @@ -385,10 +388,13 @@ describe('<SwitchBase />', () => {
expect(consoleErrorMock.callCount()).to.equal(0);

setProps({ checked: undefined });
expect(consoleErrorMock.callCount()).to.equal(1);
expect(consoleErrorMock.callCount()).to.equal(2);
expect(consoleErrorMock.args()[0][0]).to.include(
'A component is changing a controlled input of type %s to be uncontrolled.',
);
expect(consoleErrorMock.args()[1][0]).to.include(
'A component is changing a controlled SwitchBase to be uncontrolled.',
);
}),
);
});
Expand Down

0 comments on commit 84ac74f

Please sign in to comment.