Share state between components

I am working on a hobby gym management app, and I am puzzled by the mechanism of sharing state between three components in React-Native.

My three components are:

1. Schedule:

[...]
function Schedule() {
  return (
    <Stack.Navigator
      initialRouteName="Monday"
      screenOptions={{
        headerStyle: { backgroundColor: "#f58220" },
        headerTintColor: "#fff",
        headerTitleStyle: { fontWeight: "bold" },
        headerRight: () => <SwitchButton />,
      }}
    >
      <Stack.Screen
        name="TabStack"
        component={TabStack}
        options={{ title: "Aerobic Schedule" }}
      />
    </Stack.Navigator>
  );
}

export default Schedule;

I want the SwitchButton button in my Schedule component (1.) to alternate between DATA_AEROBIC and DATA_KIDS arrays props of the FlatList in (2.) based on the content of the listAerobic boolean variable.

2. MondayPage:

[...]
const MondayPage = () => {
  const [selectedId, setSelectedId] = useState(null);
  const [listAerobic, setListAerobic] = useState(true);

  const renderItem = ({ item }) => {
    const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";

    return (
      <Item
        item={item}
        onPress={() => setSelectedId(item.id)}
        style={{ backgroundColor }}
      />
    );
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1, padding: 5 }}>
        <SafeAreaView style={styles.container}>
          <FlatList
            data={listAerobic ? DATA_AEROBIC : DATA_KIDS}
            renderItem={renderItem}
            keyExtractor={(item) => item.id}
            extraData={selectedId}
          />
        </SafeAreaView>
      </View>
    </SafeAreaView>
  );
};

However, I don’t know how to link the listAerobic boolean variable to the state of the SwitchButton component (3.) , and how to make it toggle on and off.

3. SwitchButton:

const SwitchButton = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);


  return (
    <View style={styles.container}>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
      <Text> aerobic/kids</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
    marginRight: 5,
    padding: 5,
  }
});

export default SwitchButton;

Any guidance would be awesome! I mention I have really tried to look it up on different tutorials, but I can’t seem to get the gist of it. It is my first project in React/React-Native.

Many thanks!

1 thought on “Share state between components”

  1. I think you just need ‘value’ to accept a prop passed into it on the switch button. Then wherever you use switch button just pass a boolean value into it from state e.g.

    <SwitchButton enabled={this.state.switchEnabled}/>

    As for setting state ‘globally’ so this.state.switchEnabled can be updated from various places / accessible all over the app you need to look into state management tools like Redux (or I hear ‘React Hooks’ is now a thing and preferred….)

    Reply

Leave a Comment