Skip to content

Instantly share code, notes, and snippets.

@geotrev
Last active August 15, 2019 17:46
Show Gist options
  • Save geotrev/17e66171e932a04134d3364d55113515 to your computer and use it in GitHub Desktop.
Save geotrev/17e66171e932a04134d3364d55113515 to your computer and use it in GitHub Desktop.
import React from "react"
import { withLastLocation } from "react-router-last-location"
import PropTypes from "prop-types"
class AccessibleHeader extends React.Component {
constructor(props) {
super(props)
this.headerRef = React.createRef()
this.state = { tabIndex: null }
}
static propTypes = {
children: PropTypes.any.isRequired,
lastLocation: PropTypes.object.isRequired,
}
componentDidMount() {
// Don't auto-focus header if there's no lastLocation prop!
if (!this.props.lastLocation) return
this.setState({ tabIndex: "-1" }, () => {
this.headerRef.current.focus()
})
}
handleHeaderBlur = () => {
this.setState({ tabIndex: null })
}
render() {
return (
<h1 tabIndex={this.state.tabIndex} onBlur={this.handleHeaderBlur} ref={this.headerRef}>
{this.props.children}
</h1>
)
}
}
export default withLastLocation(AccessibleHeader)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment