Pro Developer
Pro Developer

Reputation: 11

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>

Upvotes: 0

Views: 1300

Answers (2)

Finney
Finney

Reputation: 1

For this is I got the alternate solution, which we can use after the page reload or refreshing the page using navigate from React.Taking the route or the url for which we want to keep the tabs to its default state , here after reloading the page the tab will move the active one with its data:-

  let [showActiveTab, setShowActiveTab] = useState("nav-home");

  const navigate = useNavigate();
  const activeTab = showActiveTab;
  useEffect(() => {
    if (activeTab) {
      navigate("/whatever route you wanna give ");
    }
  }, [activeTab])



<Tabs
id="controlled-tab-example"
className="mb-3"
>
<Tab eventKey="home" title="Home"
onClick={() => setShowActiveTab("nav-home")}>
 <h3>Home</h3>
</Tab>
<Tab eventKey="profile" title="Profile">
 <h3>Profile</h3>    
</Tab>
<Tab eventKey="contact" title="Contact">
  <h3>Contact</h3
</Tab>
</Tabs>

Upvotes: 0

Pro Developer
Pro Developer

Reputation: 11

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>

Upvotes: 1

Related Questions