Search code examples
reactjsreact-router-domreact-bootstrap

Reactjs adding the selected react-bootstrap tab key # to the current URL


I have component contain "React Bootstrap Tab", i want if user select any of these three tabs , to add to current url:-

http://localhost:3000/account

the selected tab key name, so the url change like this:-

http://localhost:3000/account#messages

I have tried by using props.history.push in onSelect function but nothing happened.

import React from "react";
import KhatmaTable from "../components/Account/KhatmasTable";
import Square from "../components/Account/Square";
import Messages from "../components/Account/Messages";
import { Tabs, Tab } from "react-bootstrap";

class Account extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user: {},
      khatmas: [],
      selectedKey: this.props.location.hash
        ? this.props.location.hash.substring(1)
        : "home",
    };
  }

  render() {
    const count = [this.state.khatmats];
    console.log(this.state.user);
    console.log(this.state.user.khatmas ? this.state.user.khatmas.length : "");
    return (
      <div className="card">
        <div className="card-body">
          <Tabs
            id="controlled-tab-example"
            activeKey={this.state.selectedKey}
            onSelect={(k) => {
              this.setState({ selectedKey: k });
              this.props.history.replace = "account" + "#" + k;
            }}
          >
            <Tab eventKey="home" title="home">
              <div className="row">
                <Square />
              </div>
            </Tab>
            <Tab eventKey="khatmat" title="profile">
              <KhatmaTable />
            </Tab>
            <Tab eventKey="messages" title="messages">
              <Messages />
            </Tab>
          </Tabs>
        </div>
      </div>
    );
  }
}
export default Account;

Solution

  • Write below function before render and modify the value part ?tab=${key} inside replace function as per your need.

    handleSelect = (key) => {
        this.setState({ key });
        this.props.history.replace({
            hash: `${key}`
        })
    }
    

    Inside Tabs, Add function name as shown below

    <Tabs onSelect={this.handleSelect} >
    

    Hope this helps.