Skip to content

Commit

Permalink
[@mantine/core] SegmentedControl: Fix error when selected item remove…
Browse files Browse the repository at this point in the history
…d from the data array (#4122)
  • Loading branch information
rtivital committed Sep 24, 2023
1 parent 38bfbcc commit 4a2226a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useState } from 'react';
import { SegmentedControl } from './SegmentedControl';
import { MantineThemeProvider } from '../../core';

Expand Down Expand Up @@ -77,3 +77,21 @@ export function FocusRingAlways() {
</div>
);
}

export function SelectedItemRemoved() {
const [value, setValue] = useState('');
const [breakingThings, setBreakingThings] = useState(false);

const dataList =
breakingThings === true ? ['1', '2', '3'].filter((elem) => elem !== '3') : ['1', '2', '3'];

return (
<div style={{ padding: 40 }}>
<SegmentedControl value={value} onChange={setValue} data={dataList} />

<button type="button" onClick={() => setBreakingThings(!breakingThings)}>
Click here to break things
</button>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -181,23 +181,27 @@ export const SegmentedControl = factory<SegmentedControlFactory>((_props, ref) =
useEffect(() => {
if (_value in refs.current && observerRef.current) {
const element = refs.current[_value];
const elementRect = element.getBoundingClientRect();
const scaledValue = element.offsetWidth / elementRect.width;
const width = element.clientWidth * scaledValue || 0;
const height = element.clientHeight * scaledValue || 0;

const offsetRight =
containerRect.width - element.parentElement!.offsetLeft + WRAPPER_PADDING - width;
const offsetLeft = element.parentElement!.offsetLeft - WRAPPER_PADDING;

setActivePosition({
width,
height,
translate: [
dir === 'rtl' ? offsetRight * -1 : offsetLeft,
element.parentElement!.offsetTop - WRAPPER_PADDING,
],
});
if (element) {
const elementRect = element.getBoundingClientRect();
const scaledValue = element.offsetWidth / elementRect.width;
const width = element.clientWidth * scaledValue || 0;
const height = element.clientHeight * scaledValue || 0;

const offsetRight =
containerRect.width - element.parentElement!.offsetLeft + WRAPPER_PADDING - width;
const offsetLeft = element.parentElement!.offsetLeft - WRAPPER_PADDING;

setActivePosition({
width,
height,
translate: [
dir === 'rtl' ? offsetRight * -1 : offsetLeft,
element.parentElement!.offsetTop - WRAPPER_PADDING,
],
});
} else {
setActivePosition({ width: 0, height: 0, translate: [0, 0] });
}
}
}, [_value, containerRect, dir]);

Expand Down

0 comments on commit 4a2226a

Please sign in to comment.