Skip to content

Instantly share code, notes, and snippets.

@jamesreggio
Created September 19, 2018 17:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesreggio/a669e1b24e37bb2492befaf2b7762cb2 to your computer and use it in GitHub Desktop.
Save jamesreggio/a669e1b24e37bb2492befaf2b7762cb2 to your computer and use it in GitHub Desktop.
Example of proposed imperative StatusBar API for React Native
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, StatusBar} from 'react-native';
const instructions = `
This app demonstrates the proposed imperative stack-manipulation methods on \`StatusBar\`.
`;
const pad = (value, width) => (
`${value}${Array(width - String(value).length).fill(' ').join('')}`
);
export default class App extends Component {
state = {
stack: [],
};
render() {
const {stack} = this.state;
const Button = ({onPress, children}) => (
<Text style={styles.button} onPress={onPress}>
{children}
</Text>
);
return (
<View style={styles.container}>
<Text style={styles.instructions}>{instructions}</Text>
<Button onPress={() => this.pushImperative({barStyle: 'light-content'})}>
Push imperative 'light-content' entry
</Button>
<Button onPress={() => this.pushImperative({barStyle: 'dark-content'})}>
Push imperative 'dark-content' entry
</Button>
<Button onPress={() => this.pushComponent({barStyle: 'light-content'})}>
Mount 'light-content' component
</Button>
<Button onPress={() => this.pushComponent({barStyle: 'dark-content'})}>
Mount 'dark-content' component
</Button>
<Button onPress={() => this.pop()}>
Pop entry
</Button>
<Text style={styles.log}>
{!stack.length ? (
'Stack empty'
) : (
stack.map(({type, props}, i) => (
`${pad(i, 2)} ${pad(type, 10)} ${JSON.stringify(props)}`
)).join('\n')
)}
</Text>
{stack.filter(({type}) => type === 'component').map(({props}, i) => (
<StatusBar key={i} {...props} />
))}
</View>
);
}
pushImperative(props) {
this.setState(({stack}) => {
const entry = StatusBar.pushStackEntry(props);
return {
stack: [
...stack,
{type: 'imperative', props, entry},
],
};
});
}
pushComponent(props) {
this.setState(({stack}) => ({
stack: [
...stack,
{type: 'component', props},
],
}));
}
pop() {
this.setState(({stack}) => {
const {type, entry} = stack.slice().pop() || {};
if (type === 'imperative') {
StatusBar.popStackEntry(entry);
}
return {stack: stack.slice(0, -1)};
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
padding: 20,
},
instructions: {
marginBottom: 20,
fontSize: 12,
color: '#333333',
},
button: {
marginBottom: 10,
fontSize: 12,
fontWeight: '700',
color: 'blue',
},
log: {
marginTop: 10,
fontSize: 12,
fontFamily: 'Menlo',
color: '#333333',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment