I have created a page with some tabs on it. Tab codes are these:
const [ toggleState, setToggleState ] = useState(1);
const toggleTab = (index) => {
setToggleState(index);
}
<div className="tab-title-Container">
<li className= {toggleState === 1 ? "tab-name active-name" : "tab-name"}
onClick={() => toggleTab(1)}>Tab1</li>
<li className= {toggleState === 2 ? "tab-name active-name" : "tab-name"}
onClick={() => toggleTab(2)}>Tab2</li>
</div>
<div className="tab-content-Container">
<div className= {toggleState === 1 ? "tab-content active-content" : "tab-content"}>
Tab1 Content</div>
<div className= {toggleState === 2 ? "tab-content active-content" : "tab-content"}>
Tab2 Content</div>
</div>
style:
.tab-content {display: none;}
.active-content {display: block;}
Now I want to create navbar links of each tab. When I click Tab2 navbar link, this page should open and Tab2 switch to active class (default active tab is Tab1). I am using react-router-dom": "^6.3.0".
I need to create routes like this "https://example.com/page=01#tab1", "https://example.com/page=01#tab2" for them.
react-router-hash-linkAFAIK hasn't been updated to be compatible withreact-router-dom@6. That said, it doesn't appear you are using the hash for normal purposes. The URLhashvalue can be read from thelocationobject and parsed to extract the numerical tab value. Use auseEffecthook to "listen" for changes to thehashto update the localtoggleStatestate.Example:
...
Like I said, this is a bit of an odd use of the URL hash. I think a query parameter would be an improved alternative.
Example:
...