Alan Souza
Alan Souza

Reputation: 7795

React router: reset focus on route change (accessibility)

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

Upvotes: 6

Views: 6940

Answers (2)

Carlos C
Carlos C

Reputation: 677

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

Upvotes: 1

Alan Souza
Alan Souza

Reputation: 7795

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);

Upvotes: 4

Related Questions