Animated Search View in React Native

October 25, 2020 - 2 min read

Lately I've been working more with animations in React Native. When it comes to that, React Native has its own API. There are some limitation though, as for example gesture handling or changing width and height of an element. For that,  I can recommend using the react-native-reanimated library.

The source code can be found here. Note: this example uses react-native-reanimated v2. I will explain the most difficult points I had with this example.

Libraries that I have used

The thing about view positioning in React Native

Some things can be tricky in React Native. As is making your code work the same way on Android and iOS. For example, when applying zIndex and absolute view positioning to a component. You may run into problems when attempting to use a scroll view inside such a component. It may not be responsive on Android, but on iOS (as in my case).

I fixed this problem by playing with the elevation property and changing the order of the absolute positioned view. This property not just adds a drop shadow to the view, but also affects its z-order.

Preventing Fetch Race Conditions

This is not just related to React Native, but to any software product. In fact, when your program relies on a specific order of executions in order to work properly, you may run into race conditions.

For example, take a button that gets pressed by a user. An each click, a request is started and on response, a counter is increased. This could lead to problem, because the counter may increase too often. Another case, specific to React, is related to its life cycle. Specifically when a request is still running, after the component has been unmounted.

import useAsyncEffect from '@n1ru4l/use-async-effect';
function* (onCancel, c) {
const controller = new AbortController();
onCancel(() => controller.abort());
const data = yield* c(search(controller));
const search = controller => fetch('someURL', { signal: controller.signal }).then(r => r.json());

This code shows how to prevent fetch race conditions. It uses a generator function and cancels requests with the AbortController when necessary.