Skip to content

Commit

Permalink
fix: set value on prop change
Browse files Browse the repository at this point in the history
  • Loading branch information
SKairinos committed Jul 3, 2023
1 parent 8141264 commit 142f8a8
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/components/page/TabBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,36 +32,40 @@ export interface TabBarProps {
path: string;
}>;
originalPath: string;
initialValue?: number;
value?: number;
}

const TabBar: React.FC<TabBarProps> = ({
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]);

Expand All @@ -86,7 +90,7 @@ const TabBar: React.FC<TabBarProps> = ({
className='flex-center'
>
<Tabs
value={value}
value={_value}
onChange={(_, value) => {
navigate(generatePath(originalPath, {
tab: paths[value]
Expand Down Expand Up @@ -123,7 +127,7 @@ const TabBar: React.FC<TabBarProps> = ({
)}
</Tabs>
</Section>
{children[value]}
{children[_value]}
</>;
};

Expand Down

0 comments on commit 142f8a8

Please sign in to comment.