<button onClick={()=>history.push("/page")}> Redirect </button>
code for /page component:
const[toggle,setToggle] = useState<boolean>(true);
return(
<div>{toggle? <Tab1Container /> : <Tab2Container />} </div>
)
there are 2 different tabs on /page, lets say tab1 and tab2, by default when you loading /page, it shows tab1 component. How can I redirect to tab2 component when I click on the button?
CodePudding user response:
You can use Link and useLocation from react-router-dom to achieve the result you want. It can be used as:
You can use the following code on the page where the button is present.
import { Link } from 'react-router-dom'
<Link
to={{
pathname: '/page',
state: {
toggleValue: false
}
}}
>
<button onClick={()=>history.push("/page")}> Redirect </button>
</Link>
On the page component
import {useLocation } from 'react-router-dom'
const location = useLocation()
const { toggleValue } = location?.state ?? {}
const[toggle,setToggle] = useState<boolean>(toggleValue);
return(
<div>{toggle? <Tab1Container /> : <Tab2Container />} </div>
)
Also, you can set toogle value on useEffect hook when page load and to change the tab on page use setToggle on handle function
CodePudding user response:
Just uplift the useState of the toggle Button or use context api or state management libraries..
From your parent component..
Pass SetToggle as props to the button component & Pass toggle as props to the Page Component
<button onClick={()=>setToggle(!toggle)}> Redirect </button>
For your reference,