0

I'm using React-router v5 and i want to use the same behavior as Link component

<form className="align-bottom d-flex align-baseline align-items-md-end form-inline float-right">
        
    ...
    <Button type="button" className={"align-center getStarted btn mx-0 "}
       onMouseDown={e => e.preventDefault()} onClick={signUpHandler}>
       <HeaderLink className={'excluded'}>Get started</HeaderLink>
    </Button>
    ...
       
</form>

i Don't want to wrap the get started button with Link because i want to check if the website is visited from small devices (then don't show a pop-up but inside an url) or desktop screen (then just show the pop-up).

Here is the login i tried so far when the get started button get clicked :

const Header = () => {
    ...
    const signUpHandler = () => {
        const mql = window.matchMedia('(max-width: 900px)')
        if (mql.matches) {
            // The viewport is less than 670px
            window.location.href = "/sign-up";
            // <Redirect to='/login' />
        } else {
            // The viewport is wider than 670px
            toggleVisibility(!isVisible);
            changeIsLogIn(false)
            // changeIsLogIn(isLogIn => false)
        }
    }
   ...
}

So, instead of window.location.href = "/sign-up"; which will reload the entire screen(on small screens) i want just to redirect the user using react-router's Link like.

Any help or advice would appreciated guys , Thank you !

3 Answers 3

1

If you have a look at the available Hooks, you will find useHistory, which will give you access to the history object. This object has a push function, which the Link component uses as well.

// import the useHistory hook from react-router
import { useHistory } from 'react-router-dom';
...
const Header = () => {
  // get the history object with useHistory
  const history = useHistory();
  ...
  const signUpHandler = () => {
    ...
    // redirect user to the sign-up page
    history.push("/sign-up");
    ...
  }
  ...
}
1
  • My bad i forget about useHistory , Thanks man
    – mhannani
    Dec 18, 2020 at 21:06
1

use the useHistory() hook.

Here you have a good doccumentation:

https://reactrouter.com/web/api/Hooks

1
import { useHistory } from "react-router-dom";

const Header = () => {
    const history = useHistory();
    ...
    const signUpHandler = () => {
        const mql = window.matchMedia('(max-width: 900px)')
        if (mql.matches) {
            // The viewport is less than 670px
            history.push("/sign-up");
        } else {
            // The viewport is wider than 670px
            toggleVisibility(!isVisible);
            changeIsLogIn(false)
            // changeIsLogIn(isLogIn => false)
        }
    }
   ...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.