Default Initial State with Prop Value
activeTab is held in TabContext
I cannot set the default state here because I don't know how to access the prop value of of Tab component in a TabContext component.
TabContext.js
const TabContext = createContext();
export function useTab() {
return useContext(TabContext);
}
const TabProvider = ({ children }) => {
const [activeTab, setActiveTab] = useState();
const toggleTab = (title) => {
setActiveTab(title);
};
return (
<TabContext.Provider value={[activeTab, toggleTab]}>
{children}
</TabContext.Provider>
);
};
export default TabProvider;
Usage
<TabProvider>
<TabContainer>
<Tab title='One' defaultTab/>
<Tab title='Two' />
</TabContainer>
</TabProvider>
Tab component
activeTab state is accessed by useTab() hooktoggleTab sets the state to whatever the input is.useEffect(), but since state changes it creates infinite loop and the activeTab is stuck on the title prop of Tab Component.const Tab = ({ title, defaultTab }) => {
const [activeTab, toggleTab] = useTab();
useEffect(() => {
if (defaultTab) {
toggleTab(title);
}
}, []);
return (
<div
className={(activeTab === title ? 'text-blue-600' : 'text-gray-900')}
onClick={() => {
toggleTab(title);
}}
>
{title}
</div>
);
};
Desired Outcome: The activeTab default state is the title prop value of Tab component when it has the prop defaultTab while allowing state to be changed afterwards based on click. Also making defaultTab prop required for one of the Tab Components under TabContainer
Does Tab component can have multiple title or single value (Like 'One', 'Two') ? If so, it is correct to use useTab component in every Tab component. And if you are trying to make tab one selected by default you can change ur Tab component like below:
const Tab = ({ title, defaultTab }) => {
const [activeTab, toggleTab] = useTab();
return (
<div
className={(activeTab === title || defaultTab ? 'text-blue-600' : 'text-gray-900')}
onClick={() => {
toggleTab(title);
}}
>
{title}
</div>
);
};
As I understand you are trying to make any tab selected by default and change the state afterwards.