I am trying to structure my problem:
What am I working on: I am trying to do a an opening hours view in react-native (typescript) where you can turn the weekdays on and off. And for the days where it is on you can set the opening hours via time picker. Just like the one of Google that you see here: Google Opening hours
What is my problem: I ran now into a styling issues. When I switch off a day the whole content jumps to the right. How should I structure and style my components?
interface Props {
day: String;
}
export function OpenTimesItem(props: Props) {
const [isOn, setOn] = useState(true);
const toggleOn = () => setOn(!isOn);
return (
<View style={styles.dayContainer}>
<Text>{props.day}</Text>
<View>
<Switch value={isOn} onValueChange={toggleOn} />
<Text>{isOn ? "Geöffnet" : "Geschlossen"}</Text>
</View>
{isOn ? (
<View style={styles.timePicker}>
<TimePicker />
<Text>-</Text>
<TimePicker />
</View>
) : (
<View style={styles.timePicker}></View>
)}
</View>
);
}
const styles = StyleSheet.create({
dayContainer: {
borderBottomWidth: 1,
borderBottomColor: "#D1D1D1",
alignItems: "center",
justifyContent: "space-between",
flexDirection: "row",
},
timePicker: {
flexDirection: "row",
alignItems: "center",
},
});
You can use flex: 1
and flex-end
to achieve what you want. Notice that I do not have your TimePicker
component, thus I've added a dummy text component instead.
import React, { useState } from "react"
import { StyleSheet, Switch, Text, View } from "react-native"
interface Props {
day: String
}
export function OpenTimesItem(props: Props) {
const [isOn, setOn] = useState(true)
const toggleOn = () => setOn(!isOn)
return (
<View style={styles.dayContainer}>
<Text style={styles.flex1}>{props.day}</Text>
<View style={[styles.flex1, { alignItems: "center" }]}>
<Switch value={isOn} onValueChange={toggleOn} />
<Text>{isOn ? "Geöffnet" : "Geschlossen"}</Text>
<View style={styles.timePicker} />
</View>
<View style={styles.flex1}>
{isOn && (
<View style={{ flexDirection: "row", alignSelf: "flex-end" }}>
<Text>10:22</Text>
<Text>-</Text>
<Text>10:25</Text>
</View>
)}
</View>
</View>
)
}
const styles = StyleSheet.create({
dayContainer: {
borderBottomWidth: 1,
borderBottomColor: "#D1D1D1",
alignItems: "center",
justifyContent: "space-between",
flexDirection: "row",
},
timePicker: {
flexDirection: "row",
alignItems: "center",
},
flex1: {
flex: 1,
},
})
This yields the following.