Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an accessible way of telling that some part of UI can redirect to other page if some asynchronous condition is resolved after clicking link?

Let's say I have the following component

function ClickButton(props) {
  const history = useHistory();

  const onClick = () => {
    history.push('/next-page');
  };

  return <button onClick={onClick}>Go to next page</button>;
}

More accessible version would be to use Link from react-router as the following

function ClickButton(props) {
  return (
    <Link to="/next-page">
      <span>Go to next page</span>
    </Link>
  );
}

But what if redirection depends on some http call success, like

function ClickButton(props) {
  const history = useHistory();

  const onClick = async () => {
    try {
      await axios.get('https://google.com')
      history.push('/next-page');
    } catch(err) {
      setAlertMessage('Google can't be reached - check your internet connection');
    }
  };

  return <button onClick={onClick}>Go to next page</button>;
}

What is equivalent (and is there some semantically meaningful way) of using Link (or something else that e.g. screen readers would treat as link-alike) here, in case of async handler of onClick event?

like image 999
zmii Avatar asked Jan 29 '26 20:01

zmii


1 Answers

I'd probably opt to use the Link component since semantically it makes the most sense to. You can use button element, but then you would need to add all the appropriate accessibility attributes, i.e. role="link" and correct click and keypress event handlers, etc...

You can add an onClick handler to the Link and do the same check. The key is preventing initially the default link behavior.

const ClickButton = props => {
  const history = useHistory();

  const onClick = async e => {
    e.preventDefault();
    try {
      await axios.get("https://google.com"); // NOTE *
      history.push("/next-page");
    } catch (err) {
      alert("Google can't be reached - check your internet connection");
    }
  };

  return (
    <Link to="/next-page" onClick={onClick}>
      <span>Go to next page</span>
    </Link>
  );
};

Edit link async check GET request

* NOTE: this GET request seems to just fail in codesandbox.

like image 188
Drew Reese Avatar answered Jan 31 '26 09:01

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!