Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@asgvard
Last active April 13, 2019 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asgvard/53879f55081eec02f88fdbbaeba6a806 to your computer and use it in GitHub Desktop.
Save asgvard/53879f55081eec02f88fdbbaeba6a806 to your computer and use it in GitHub Desktop.
Spatial Navigation article. Distributed logic example
const HomeScreen extends PureComponent {
constructor(props) {
this.state = {
focusedIndex: 0
};
this.onKeyPress = this.onKeyPress.bind(this);
}
componentDidMount() {
window.addEventListener('keydown', this.onKeyPress);
}
componentWillUnmount() {
window.removeEventListener('keydown', this.onKeyPress);
}
componentDidUpdate(oldProps) {
const {active} = this.props;
if (oldProps.active !== active) {
this.setState({
focusedIndex: 0
});
}
}
onKeyPress({keyCode}) {
const {active, rows} = this.props;
const {focusedIndex} = this.state;
if (!active) {
return;
}
let newIndex;
switch(keyCode) {
case KEY_UP:
newIndex = focusedIndex - 1;
break;
case KEY_DOWN:
newIndex = focusedIndex + 1;
break;
default:
break;
}
this.setState({
focusedIndex: Math.clamp(newIndex, 0, rows.length - 1)
});
}
render() {
const {rows} = this.props;
const {focusedIndex} = this.state;
return (<React.Fragment>
{rows.map((rowData, index) => (<GalleryRow
key={rowData.id}
active={index === focusedIndex}
items={rowData.items}
/>))}
</React.Fragment>);
}
}
const GalleryRow extends PureComponent {
// same logic that handles switching focus between gallery items
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment