Instantly share code, notes, and snippets.
asgvard/spatial-nav-distributed-logic.js
Last active Apr 13, 2019
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