Component Details: This is a tab component where the tab buttons are horizontally scrollable
Problem: When i scroll horizontally and click on a tab button. The horizontal scroll is reset. Maybe The entire tab container is re-rendering due to the setState IDK.
Expecting: I want to be able to click on a tab button and not update the horizontal scroll position of the button container.
Current Code:
function Tabs(props) {
const [tabState, setTabState] = useState(0);
const [menuData, setMenuData] = useState('')
const TabContainer = styled.div`
width: 100%;
display: flex;
flex-wrap: no-wrap;
flex-direction: row;
margin: 0 0 20px 0;
padding: 20px;
align-items: flex-start;
justify-content: flex-start;
background-color: #fff;
overflow-x: auto;
const handleTabClick = (index) => {
setTabState(index);}return(
<>
<TabParent>
<TabContainer>
{props.data && props.data.dataDeets.map((dataDeets,catIndex) => {
return (
<TabBtn key={catIndex} onClick={() => handleTabClick(catIndex) } active={tabState === catIndex ? true : false}>
{menu.category}
</TabBtn>
)
})
}
</TabContainer>
</TabParent>
{props.data && props.data.menu.map((menu, catIndex) => {
return (
<TabCont key={catIndex} active={tabState === catIndex ? true : false}>
<small>
{data.categoryDesc}
</small>
{data.items.map((items, itemIndex) => {
return (
<div key={itemIndex} onClick={event => props.openDetails(catIndex, itemIndex, event)}>
<ItemCard key={itemIndex} title={items.title} imgurl={items.imgurl} desc={items.desc} price={items.price} />
</div>
)
})
}
</TabCont>
)
})
}
</>
);
My Rookie mistake: Hopefully this will helps other rookies :)
useState caused the entire component to re-render
My Solution Move the out as a separate component. This enables To maintain its own state.