To redirect a user on a button click, you can use the push()
function from react-router-dom
. Additionally, you can add props to the pushed object adding another property to it:
javascripthistory.push({ pathname: '/link', prop: 'Whatever', })
You can choose the prop
property name.
Example:
jsximport React from 'react' import { useHistory } from 'react-router-dom' const Redirect = () => { const history = useHistory() const redirect = () => { history.push({ pathname: '/main', message: 'My name is Erik' }) } return <button onClick = {redirect}>Go to main</button> } export default Redirect
After the redirection, you can read the props passed by the previous component:
jsximport React from 'react' import { useLocation } from 'react-router-dom' const Main = () => { const location = useLocation() useEffect(() => { console.log(location.message) // My name is Erik }, []) return <div>Whatever</div> } export default Redirect
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.