Instantly share code, notes, and snippets.
Last active
April 13, 2019 19:00
Spatial Navigation article. Distributed logic example
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
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