Last active
February 17, 2019 22:39
-
-
Save geotrev/f93db9116f80cb9d2eab5b615086682e to your computer and use it in GitHub Desktop.
An accessible page header component for SPAs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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