Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 812
Alan Souza Avatar asked Jun 22 '16 00:06

Alan Souza


2 Answers

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);
like image 100
Alan Souza Avatar answered Sep 26 '22 04:09

Alan Souza


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

like image 40
Carlos C Avatar answered Sep 25 '22 04:09

Carlos C