6

I'm trying to improve accessibility in my existing app and I've noticed that when my route changes the browser focus remains unchanged. My expectation was for the focus to be back in the first element on the page so that I can take advantage of skip links and things like that.

Question: is there a way to reset the browser focus (emulating a page refresh) using react-router?

UPDATE 1:

I tried adding document.activeElement.blur() which seems to help, but is not working in Chrome.

UPDATE 2:

Actually even after removing document.activeElement.blur() it seems to work in Safari. I wonder if this is something related to browserHistory from react-router

Alan Souza
  • 7,475
  • 10
  • 46
  • 68

2 Answers2

4

The solution I ended up going for was to update my react container to have tabindex="-1" and call document.getElementById('content').focus() inside onUpdate. This feels like a hack to me, so I'm not sure if this is the right solution.

index.html

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta charset="UTF-8">
  <title>Todo App</title>
  <meta name="description" content="" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta name="mobile-web-app-capable" content="yes">
</head>
<body>
  <div id="content" tabindex="-1" />
  <script src="index.js"></script>
</body>
</html>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';

import routes from './routes';

let element = document.getElementById('content');
ReactDOM.render(<Router onUpdate={() => document.getElementById('content').focus()}
  history={browserHistory} routes={routes} />, element);
Alan Souza
  • 7,475
  • 10
  • 46
  • 68
  • 1
    You hack has 2 parts. 1) tabindex to -1. That's not hacky, you'll always end up putting it somewhere that cannot be focussed normally (an element that's not a button, link, etc). 2) calling focus on the outer element from within of your React app. You could argue that this is indeed a bit dirty. You can make it a bit less by calling `element.focus()`, but it's still the same. Or wrap your router in another jsx element and the focus on that one (hint use a `ref`). – Tieme Oct 10 '16 at 18:29
1

This question is a bit old but I'll still share what I did. I used the autofocus prop on the components that I wanted the focus to be on navigation. I think using a prop is more natural on React than accessing

Carlos C
  • 637
  • 3
  • 17