How to redirect to an external url using React useEffect?

Asked

Viewed 203 times

0

I am trying to redirect to an external url ,using the vaiparala function by passing a parameter that I pick up from the click, the path arrives at the function correctly but the redirect does not is done , what I might be doing wrong ?

React.useEffect(() => {
    const vaiparala = (caminho) => {
      console.log(caminho);
      caminho === 'Linkedin' ? (
        <Link to={"https://www.linkedin.com/feed/"} />
      ) : (
        history.push(`/${caminho}`)
      );
    };
    const handleClick = (e) => {
      const items = document.getElementsByClassName('context-menu-item');

      if (items && items.length > 0) {
        let count = 0;
        for (let i = 0; i < items.length; i++) {
          if (items[i].contains(e.target)) {
            vaiparala(rotasClick[i]);
            count++;
          }
        }
        if (count === 0) {
          setActive(false);
        }
      } else {
        setActive(false);
      }
    };
    document.addEventListener('click', handleClick);
    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, []);

1 answer

1

You cannot redirect to an external URL using react-router - Link, Redirect or history.push.

But you can do it: window.location.href = 'https://www.linkedin.com/feed/' or window.location.replace('https://www.linkedin.com/feed/').

React.useEffect(() => {
    const vaiparala = (caminho) => {
      console.log(caminho);
      caminho === 'Linkedin' ? (
        window.location.href = 'https://www.linkedin.com/feed/'
        // ou
        window.location.replace('https://www.linkedin.com/feed/')
      ) : (
        history.push(`/${caminho}`)
      );
    };
    // ...
  • 1

    It worked perfectly, thank you very much !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.