Skip to content

Instantly share code, notes, and snippets.

@geotrev
Last active February 17, 2019 22:39
Show Gist options
  • Save geotrev/f93db9116f80cb9d2eab5b615086682e to your computer and use it in GitHub Desktop.
Save geotrev/f93db9116f80cb9d2eab5b615086682e to your computer and use it in GitHub Desktop.
An accessible page header component for SPAs.
import React, { Component } from "react"
import { withLastLocation } from "react-router-last-location"
import PropTypes from "prop-types"
class PageHeader extends Component {
constructor(props) {
super(props)
this.headerRef = React.createRef()
}
state = { tabIndex: null }
static propTypes = {
children: PropTypes.node.isRequired,
lastLocation: PropTypes.object.isRequired,
}
componentDidMount() {
if (!this.props.lastLocation) return
this.setState({ tabIndex: "-1" }, () => {
this.headerRef.current.focus()
this.headerRef.current.addEventListener("blur", this.handleHeaderBlur)
})
}
handleHeaderBlur = () => {
this.headerRef.current.removeEventListener("blur", this.handleHeaderBlur)
this.setState({ tabIndex: null })
}
render() {
return (
<h1 tabIndex={this.state.tabIndex} ref={this.headerRef}>
{this.props.children}
</h1>
)
}
}
export default withLastLocation(PageHeader)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment