Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change the URL without using <Link> component?

In react, one can use the <Link> component to change the URL when the user clicks on the <Link>.

However, this is not what I want.

I need to change the URL when a useState value changes. So I need to change the URL inside of a useEffect.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can this be done?

>Solution :

If you want to use dynamic URL use can use below approach

const [link, setLink] = useState('/profile');

useEffect(() => {
 // logic
 setLink('/logout');
}, [state you want]);

return (
 <div>
  <Link to={link} />
 </div>
);

or you want to go to a URL after some logic

const history = useHistory();

useEffect(() => {
 // logic
 history.push('/profile');
}, [some state])

To use useHistory you want import like import { useHistory } from "react-router-dom";

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading