Skip to content

Commit 1a7ac92

Browse files
authored
fix: fundamental Switch state doesn't refresh (#1193)
1 parent a9047cf commit 1a7ac92

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/Switch/Switch.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import FormLabel from '../Forms/FormLabel';
44
import keycode from 'keycode';
55
import PropTypes from 'prop-types';
66
import SwitchItem from './_SwitchItem';
7-
import React, { useCallback, useState } from 'react';
7+
import React, { useCallback, useEffect, useState } from 'react';
88
import 'fundamental-styles/dist/icon.css';
99
import 'fundamental-styles/dist/switch.css';
1010

@@ -31,6 +31,10 @@ const Switch = React.forwardRef(({
3131

3232
let [isChecked, setIsChecked] = useState(!!checked);
3333

34+
useEffect(() => {
35+
setIsChecked(!!checked);
36+
}, [checked]);
37+
3438
const handleChange = (e) => {
3539
setIsChecked(!isChecked);
3640
onChange(e);

src/Switch/Switch.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,28 @@ describe('<Switch />', () => {
6363
).toBe('Sample');
6464
});
6565
});
66+
67+
describe('Switch state change on props update', () => {
68+
const wrapper = mount(<Switch checked />);
69+
70+
test('should change to not checked state if new props are sent with checked as false', () => {
71+
//updating prop to checked as false
72+
wrapper.setProps({ checked: false });
73+
wrapper.update();
74+
75+
// check that switch is not checked
76+
expect(wrapper.find('input').props().checked).toBe(false);
77+
expect(wrapper.find('input').props()['aria-checked']).toBe(false);
78+
});
79+
80+
test('should change to checked state if new props are sent with checked as true', () => {
81+
//updating prop to checked as true
82+
wrapper.setProps({ checked: true });
83+
wrapper.update();
84+
85+
// check that switch is checked
86+
expect(wrapper.find('input').props().checked).toBe(true);
87+
expect(wrapper.find('input').props()['aria-checked']).toBe(true);
88+
});
89+
});
6690
});

0 commit comments

Comments
 (0)