From 142f8a83fc5b0a5f363c26ff337b58f9fca6c9a5 Mon Sep 17 00:00:00 2001 From: SKairinos Date: Mon, 3 Jul 2023 13:44:47 +0100 Subject: [PATCH] fix: set value on prop change --- src/components/page/TabBar.tsx | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/components/page/TabBar.tsx b/src/components/page/TabBar.tsx index 69af1a6e..4f771a7f 100644 --- a/src/components/page/TabBar.tsx +++ b/src/components/page/TabBar.tsx @@ -32,36 +32,40 @@ export interface TabBarProps { path: string; }>; originalPath: string; - initialValue?: number; + value?: number; } const TabBar: React.FC = ({ header, tabs, originalPath, - initialValue = 0 + value = 0 }) => { const params = useParams(); const navigate = useNavigate(); - const [value, setValue] = React.useState( - initialValue < 0 + const [_value, _setValue] = React.useState( + value < 0 ? 0 - : initialValue >= tabs.length + : value >= tabs.length ? tabs.length - 1 - : initialValue + : value ); const labels = tabs.map(tab => tab.label); const children = tabs.map(tab => tab.children); const paths = tabs.map(tab => tab.path); + React.useEffect(() => { + _setValue(value); + }, [value]); + React.useEffect(() => { const tab = tryValidateSync(params, YupObject({ tab: YupString().oneOf(paths).required() }))?.tab; if (tab !== undefined) { - setValue(paths.indexOf(tab)); + _setValue(paths.indexOf(tab)); } }, [params]); @@ -86,7 +90,7 @@ const TabBar: React.FC = ({ className='flex-center' > { navigate(generatePath(originalPath, { tab: paths[value] @@ -123,7 +127,7 @@ const TabBar: React.FC = ({ )} - {children[value]} + {children[_value]} ; };