Skip to content

Instantly share code, notes, and snippets.

@imgiseverything
Last active June 23, 2021 13:22
Show Gist options
  • Save imgiseverything/cd1ac35d09ad5ae2f1ad5ed36035ad3a to your computer and use it in GitHub Desktop.
Save imgiseverything/cd1ac35d09ad5ae2f1ad5ed36035ad3a to your computer and use it in GitHub Desktop.
Parent state is reset when child function runs
/* .tsx */
import React, { useState, useCallback } from 'react';
// Tab list options, nothing fancy
const options = [
{ label: 'Option 1', value: '1'},
{ label: 'Option 2', value: '2'},
{ label: 'Option 3', value: '3'},
]
// a List of buttons, click a button to set it as active.
// Note: the first button should be marked as active when the page first renders (unless otherwise stated)
const TabList = (props: {
activeTab: string;
onTabChange: (tab: string) => void;
}) => {
const { activeTab, onTabChange } = props;
return (
<>
{options.map(({ value, label }) => {
return (
<button
key={value}
aria-selected={activeTab === value}
type="button"
onClick={() => onTabChange(value)}
>
{label}
</button>
);
})}
</>
);
}
// This parent component also needs to know which tab is active so it can display the tabPanel (not shown here in this simple gist)
const Parent = () => {
// If Option 3 in TabList is clicked, activeTab becomes '3' but then in Cypress (and only Cypress)
// it is quickly reset to '1' because Parent is rerendered
const [activeTab, setActiveTab] = useState('1');
const handleTabChange = useCallback(setActiveTab, [setActiveTab]);
return (
<div>
<h2>Parent title</h2>
<TabList activeTab={activeTab} onTabChange={handleTabChange} />
{activeTab === '3' && (<>Show TabPanel 3</div>)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment