Search code examples
react-bootstrap

Reactjs Bootstrap tab active after page reload. Or how can I save active tabs using react redux on state when page reloading


How can I save current active tabs when page reloading?

<Tabs defaultActiveKey="profile" id="uncontrolled-tab-example" className="mb-3">
  <Tab eventKey="home" title="Home">
    <Sonnet />
  </Tab>
  <Tab eventKey="profile" title="Profile">
    <Sonnet />
  </Tab>
  <Tab eventKey="contact" title="Contact" disabled>
    <Sonnet />
  </Tab>
</Tabs>

Solution

  • Here I got the solution for tab activate even after reloading the page

    const [key, setKey] = useState("Home");
    
    useEffect(() => {
    const getActiveTab = JSON.parse(localStorage.getItem("activeTab"));
     if (getActiveTab) {
     setKey(getActiveTab);
     }
    }, []);
    
    useEffect(() => {
    localStorage.setItem("activeTab", JSON.stringify(key));
    }, [key]);
    
    
    <Tabs
    id="controlled-tab-example"
    activeKey={key}
    onSelect={(k) => setKey(k)}
    className="mb-3"
    >
    <Tab eventKey="home" title="Home">
     <h3>Home</h3>
    </Tab>
    <Tab eventKey="profile" title="Profile">
     <h3>Profile</h3>    
    </Tab>
    <Tab eventKey="contact" title="Contact">
      <h3>Contact</h3> 
    </Tab>
    </Tabs>