1

I followed a react native tutorial that builds a todo list(and stores todo items with useState) and I wanted to add delete-todo item functionality. I put a delete button(using Icon react native elements) on the navbar(in App(App.js) component's return):

<NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen
            name="home"
            component={HomeScreen}
            options={({ navigation }) => ({
              headerRight: () => (
                <View>
                  <Icon
                    ...
                    onPress={() => HomeScreen.deleteSelected()}
                  />
                </View>
              ),
            })}
          />
          ...
        </Stack.Navigator>
</NavigationContainer>

However, this doesn't work since deleteSelected is a local function defined in HomeScreen(HomeScreen.js) component:

export default function HomeScreen({ navigation }) {
  ...
  const [items, setItems] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);


  const deleteSelected = () => {...}

I defined deleteSelected inside the HomeScreen component since the required states(items and selectedItems) are defined there.

After some research, I found I can implement such a trigger using forwardRef and useImperativeHandle as shown in https://stackoverflow.com/a/65389631/20883133 . I am wondering if there is a cleaner(more versatile) way to implement a function trigger from the parent component to a function in the child component in react native.

I was told some state manager dependencies can help, like Zustand or Recoil. I read recoil docs in detail but couldn't figure out how it can help with such a problem.

Jatin Bhuva
  • 1,301
  • 1
  • 4
  • 22
JSmambo
  • 11
  • 3

0 Answers0