Skip to content

Instantly share code, notes, and snippets.

@janithl
Last active July 4, 2021 18:22
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 janithl/0228731f9fff1b10371a836ecc0110fb to your computer and use it in GitHub Desktop.
Save janithl/0228731f9fff1b10371a836ecc0110fb to your computer and use it in GitHub Desktop.
A simple React Native component to select slots in a timeline
import React, { useState } from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const SlotSelector = () => {
const [selected, setSelected] = useState([0, 0]);
const slots = [1, 2, 3, 4, 5, 6, 7, 8];
const onSelect = (index: number) => {
if (selected[0] === selected[1] && selected[1] === 0) {
setSelected([index, index]);
} else if (selected[0] === selected[1] && selected[1] === index) {
setSelected([0, 0]);
} else if (index === selected[0] - 1) {
setSelected([index, selected[1]]);
} else if (index === selected[0]) {
setSelected([index + 1, selected[1]]);
} else if (index === selected[1] + 1) {
setSelected([selected[0], index]);
} else if (index === selected[1]) {
setSelected([selected[0], index - 1]);
}
};
return (
<View style={styles.container}>
{slots.map(slot => (
<Slot key={slot} index={slot} selected={selected} onSelect={onSelect} />
))}
</View>
);
};
const Slot = ({ index, selected, onSelect }: SlotProps) => {
let text = '';
if (selected[0] === selected[1] && selected[1] === 0) {
text = '';
} else if (index === selected[0] || index === selected[1]) {
text = '-';
} else if (index === selected[0] - 1 || index === selected[1] + 1) {
text = '+';
}
return (
<TouchableOpacity onPress={() => onSelect(index)}>
<View
style={
index >= selected[0] && index <= selected[1]
? [styles.box, styles.boxSelected]
: styles.box
}
>
<Text style={styles.boxText}>{text}</Text>
</View>
</TouchableOpacity>
);
};
type SlotProps = {
index: number;
selected: number[];
onSelect: (index: number) => void;
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row'
},
box: {
width: 40,
height: 40,
backgroundColor: '#eee',
marginRight: 1,
justifyContent: 'center'
},
boxSelected: {
backgroundColor: '#c0c0c0'
},
boxText: {
textAlign: 'center'
}
});
export default SlotSelector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment