├── .buckconfig
├── .bundle
└── config
├── .eslintrc.js
├── .gitignore
├── .node-version
├── .prettierrc.js
├── .ruby-version
├── .watchmanconfig
├── App.tsx
├── Gemfile
├── README.md
├── __tests__
└── App-test.tsx
├── android
├── app
│ ├── _BUCK
│ ├── build.gradle
│ ├── build_defs.bzl
│ ├── debug.keystore
│ ├── proguard-rules.pro
│ └── src
│ │ ├── debug
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── infinitescroll
│ │ │ └── ReactNativeFlipper.java
│ │ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ └── com
│ │ │ └── infinitescroll
│ │ │ ├── MainActivity.java
│ │ │ ├── MainApplication.java
│ │ │ └── newarchitecture
│ │ │ ├── MainApplicationReactNativeHost.java
│ │ │ ├── components
│ │ │ └── MainComponentsRegistry.java
│ │ │ └── modules
│ │ │ └── MainApplicationTurboModuleManagerDelegate.java
│ │ ├── jni
│ │ ├── CMakeLists.txt
│ │ ├── MainApplicationModuleProvider.cpp
│ │ ├── MainApplicationModuleProvider.h
│ │ ├── MainApplicationTurboModuleManagerDelegate.cpp
│ │ ├── MainApplicationTurboModuleManagerDelegate.h
│ │ ├── MainComponentsRegistry.cpp
│ │ ├── MainComponentsRegistry.h
│ │ └── OnLoad.cpp
│ │ └── res
│ │ ├── drawable
│ │ └── rn_edit_text_material.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── strings.xml
│ │ └── styles.xml
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
├── app.json
├── babel.config.js
├── index.tsx
├── ios
├── .xcode.env
├── InfiniteScroll.xcodeproj
│ ├── project.pbxproj
│ └── xcshareddata
│ │ └── xcschemes
│ │ └── InfiniteScroll.xcscheme
├── InfiniteScroll
│ ├── AppDelegate.h
│ ├── AppDelegate.mm
│ ├── Images.xcassets
│ │ ├── AppIcon.appiconset
│ │ │ └── Contents.json
│ │ └── Contents.json
│ ├── Info.plist
│ ├── LaunchScreen.storyboard
│ └── main.m
├── InfiniteScrollTests
│ ├── InfiniteScrollTests.m
│ └── Info.plist
└── Podfile
├── metro.config.js
├── package.json
├── src
├── assets.d.ts
├── assets
│ ├── arrow-left.png
│ ├── cat.jpg
│ ├── screenshot-1.jpg
│ └── screenshot-2.jpg
├── components
│ ├── Border
│ │ └── index.tsx
│ ├── Button
│ │ ├── index.tsx
│ │ └── styles.ts
│ └── Cats
│ │ ├── CatCard
│ │ └── index.tsx
│ │ ├── index.tsx
│ │ └── types
│ │ └── index.d.ts
├── hooks
│ └── useCats.ts
├── layout
│ └── AppLayout.tsx
├── navigation
│ ├── AppNavigation.tsx
│ └── RootNavigation.tsx
└── screens
│ ├── Cat
│ ├── index.tsx
│ └── styles.ts
│ ├── Cats
│ ├── index.tsx
│ └── styles.ts
│ └── Home
│ ├── index.tsx
│ └── styles.ts
├── tsconfig.json
└── yarn.lock
/.buckconfig:
--------------------------------------------------------------------------------
1 |
2 | [android]
3 | target = Google Inc.:Google APIs:23
4 |
5 | [maven_repositories]
6 | central = https://repo1.maven.org/maven2
7 |
--------------------------------------------------------------------------------
/.bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: '@react-native-community',
4 | parser: '@typescript-eslint/parser',
5 | plugins: ['@typescript-eslint'],
6 | overrides: [
7 | {
8 | files: ['*.ts', '*.tsx'],
9 | rules: {
10 | '@typescript-eslint/no-shadow': ['error'],
11 | 'no-shadow': 'off',
12 | 'no-undef': 'off',
13 | },
14 | },
15 | ],
16 | };
17 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | ios/.xcode.env.local
24 |
25 | # Android/IntelliJ
26 | #
27 | build/
28 | .idea
29 | .gradle
30 | local.properties
31 | *.iml
32 | *.hprof
33 | .cxx/
34 |
35 | # node.js
36 | #
37 | node_modules/
38 | npm-debug.log
39 | yarn-error.log
40 |
41 | # BUCK
42 | buck-out/
43 | \.buckd/
44 | *.keystore
45 | !debug.keystore
46 |
47 | # fastlane
48 | #
49 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
50 | # screenshots whenever they are needed.
51 | # For more information about the recommended setup visit:
52 | # https://docs.fastlane.tools/best-practices/source-control/
53 |
54 | **/fastlane/report.xml
55 | **/fastlane/Preview.html
56 | **/fastlane/screenshots
57 | **/fastlane/test_output
58 |
59 | # Bundle artifact
60 | *.jsbundle
61 |
62 | # Ruby / CocoaPods
63 | /ios/Pods/
64 | /vendor/bundle/
65 |
--------------------------------------------------------------------------------
/.node-version:
--------------------------------------------------------------------------------
1 | 16
2 |
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | arrowParens: 'avoid',
3 | bracketSameLine: true,
4 | bracketSpacing: true,
5 | singleQuote: true,
6 | trailingComma: 'all',
7 | };
8 |
--------------------------------------------------------------------------------
/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.7.5
2 |
--------------------------------------------------------------------------------
/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { StatusBar } from 'react-native';
3 | import { QueryClient, QueryClientProvider } from 'react-query';
4 |
5 | import Border from './src/components/Border';
6 | import AppLayout from './src/layout/AppLayout';
7 | import RootNavigation from './src/navigation/RootNavigation';
8 |
9 | const queryClient = new QueryClient();
10 |
11 | const App = () => {
12 | return (
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | );
21 | };
22 |
23 | export default App;
24 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby '2.7.5'
5 |
6 | gem 'cocoapods', '~> 1.11', '>= 1.11.2'
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## The Problem
2 |
3 | Since I first began using React Native, I have encountered this warning at least a dozen times, or maybe you too:
4 |
5 | ```bash
6 | VirtualizedList: You have a large list that is slow to update — make sure your renderItem function renders components that follow React performance best practices like PureComponent, shouldComponentUpdate, React.memo, useCallback, useMemo etc.
7 | ```
8 |
9 | Right, it seems familiar isn't it? This typically occurs when we load up a FlatList with lots of items that aren't just static text or images but instead have components with animations or data from third party api or other interactions.
10 |
11 | ## Why FlashList?
12 |
13 | The listing interface used by `FlatList`, which is based on ScrollView, is termed VirtualizedList. Under the hood, VirtualizedList makes use of a rendering API that renders an enumerable list of items as a scroll. Perhaps because we use the newest iPhone and effortlessly post to Instagram every day, we don't see it. Even if everything appears to be in order, you can still encounter this problem if your project runs on low-end devices, particularly Android ones. Simply put, in order to figure it out, such strategies also require some computations.
14 |
15 | Here comes to rescue `FlashList`, An alternative to FlatList that uses the UI thread and, according to their website, is 10 times quicker in JS and 5 times faster in JS thread. These performance gains are pretty impressive, even if only half the improvement is taken into account.
16 |
17 | ## Initializing React Native App
18 |
19 | We will use **React Native CLI** to create our app. Make sure to check out their [installation guide](https://reactnative.dev/docs/environment-setup) if you haven't. I will be using TypeScript in this project.
20 |
21 | To get started run this command :
22 |
23 | ```bash
24 | npx react-native init InfiniteScroll --template react-native-template-typescript
25 | ```
26 |
27 | Now wait until the installation is finished and then navigate to that directory.
28 |
29 | ```bash
30 | cd InfiniteScroll
31 | ```
32 |
33 | ## Installing Dependencies
34 |
35 | We will be using `React Navigation` in the project.Install the dependencies by running the command below. Here i'm using yarn you can use npm too.
36 |
37 | ```bash
38 | yarn add @shopify/flash-list react-query @react-navigation/native react-native-screens react-native-safe-area-context @react-navigation/native-stack
39 | ```
40 |
41 | ## Setting up React Query
42 |
43 | In order to use react-query in our project we need to setup some things. So, open you App.tsx file and add the following code.
44 |
45 | ```js
46 | import React from 'react';
47 | import { StatusBar, StyleSheet, View } from 'react-native';
48 | import { QueryClient, QueryClientProvider } from 'react-query';
49 |
50 | const queryClient = new QueryClient();
51 |
52 | const App = () => {
53 | return (
54 |
55 |
56 |
57 | Hello, World
58 |
59 |
60 | );
61 | };
62 |
63 | const styles = StyleSheet.create({
64 | container: {
65 | flex: 1,
66 | width: '100%',
67 | height: '100%',
68 | backgroundColor: '#201d29',
69 | },
70 | });
71 |
72 | export default App;
73 | ```
74 |
75 | > Note: I wont be covering the styling part. You can add your own styles or copy mine.
76 |
77 | ## Creating Components
78 |
79 | Now before moving ahead let's setup React Navigation. First create a folder `src` in the root of the project. Then create two new folders `navigation` and `screens` in `src`. In the navigation folder add two files `AppNavigation.tsx` and `RootNavigation.tsx`. `RootNavigation.tsx` will contain the NavigationContainer and the Stack Navigator exported from `AppNavigation.tsx`. Now add 2 files in the `screens` folder, `Cats.tsx` and `Cat.tsx` and export a default component from each file. Now add the following code in both `AppNavigation.tsx` and `RootNavigation.tsx`.
80 |
81 | In `AppNavigation.tsx` :
82 |
83 | ```js
84 | import { createNativeStackNavigator } from '@react-navigation/native-stack';
85 | import React from 'react';
86 | import { CatType } from '../components/Cats/types';
87 |
88 | import CatScreen from '../screens/Cat';
89 | import CatsScreen from '../screens/Cats';
90 | import HomeScreen from '../screens/Home';
91 |
92 | export type AppStackParams = {
93 | HomeScreen: undefined;
94 | CatsScreen: undefined;
95 | CatScreen: CatType;
96 | };
97 |
98 | const AppStack = createNativeStackNavigator();
99 |
100 | const AppNavigation = () => {
101 | return (
102 |
104 |
105 |
106 |
107 |
108 | );
109 | };
110 |
111 | export default AppNavigation;
112 | ```
113 |
114 | In `RootNavigation.tsx` :
115 |
116 | ```js
117 | import { DefaultTheme, NavigationContainer } from '@react-navigation/native';
118 | import React from 'react';
119 | import AppNavigation from './AppNavigation';
120 |
121 | const theme = Object.freeze({
122 | ...DefaultTheme,
123 | colors: {
124 | ...DefaultTheme.colors,
125 | background: '#201d29',
126 | },
127 | });
128 |
129 | const RootNavigation = () => {
130 | return (
131 |
132 |
133 |
134 | );
135 | };
136 |
137 | export default RootNavigation;
138 | ```
139 |
140 | Update the `App.tsx` file with the following code :
141 |
142 | ```js
143 | import React from 'react';
144 | import { StatusBar, View } from 'react-native';
145 | import { QueryClient, QueryClientProvider } from 'react-query';
146 | import RootNavigation from './src/navigation/RootNavigation';
147 |
148 | const queryClient = new QueryClient();
149 |
150 | const App = () => {
151 | return (
152 |
153 |
154 |
155 |
156 |
157 |
158 | );
159 | };
160 |
161 | const styles = StyleSheet.create({
162 | container: {
163 | flex: 1,
164 | width: '100%',
165 | height: '100%',
166 | backgroundColor: '#201d29',
167 | },
168 | });
169 |
170 | export default App;
171 | ```
172 |
173 | ## Creating Components
174 |
175 | Navigation looks okay so to get started let's first create some components. First create a directory called `src` in your root folder. Inside `src` create two new folders `components` and `hooks`. Now create a folder `Cats` inside `components` and inside that create `index.jsx` and `CatCard.jsx` file.
176 |
177 | In `CatCard.tsx` add the following code :
178 |
179 | ```js
180 | import React from 'react';
181 | import { useNavigation } from '@react-navigation/native';
182 | import { NativeStackNavigationProp } from '@react-navigation/native-stack';
183 | import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
184 |
185 | import { AppStackParams } from '../../../navigation/AppNavigation';
186 | import { CatType } from '../types';
187 |
188 | const CatCard: React.FC<{ item: CatType; index: number }> = ({
189 | item,
190 | index,
191 | }) => {
192 | const { image, name, origin } = item;
193 | const navigation = useNavigation>();
194 |
195 | return (
196 |
197 | navigation.navigate('CatScreen', item)}>
201 |
206 | {name}
207 | {origin}
208 |
209 |
210 | );
211 | };
212 |
213 | const styles = StyleSheet.create({
214 | container: {
215 | width: 170,
216 | padding: 12,
217 | borderRadius: 10,
218 | marginBottom: 20,
219 | backgroundColor: '#403c4a',
220 | alignItems: 'center',
221 | justifyContent: 'center',
222 | },
223 | image: {
224 | width: 70,
225 | height: 70,
226 | borderRadius: 80,
227 | },
228 | name: {
229 | color: '#f4f2fb',
230 | fontSize: 16,
231 | fontWeight: 'bold',
232 | marginTop: 10,
233 | },
234 | origin: {
235 | color: '#b1acb9',
236 | fontSize: 12,
237 | fontWeight: '600',
238 | marginBottom: 5,
239 | },
240 | });
241 |
242 | export default CatCard;
243 | ```
244 |
245 | Don't worry about the `index` prop. We will be using it later.
246 |
247 | Here we're importing `CatTpe` from `types` folder. So add a types folder and a `index.ts` file and add the following code :
248 |
249 | ```js
250 | export type CatType = {
251 | id: string,
252 | name: string,
253 | origin: string,
254 | description: string,
255 | life_span: string,
256 | temperament: string,
257 | adaptability: number,
258 | child_friendly: number,
259 | stranger_friendly: number,
260 | wikipedia_url: string,
261 | image: {
262 | width: number,
263 | height: number,
264 | id: string,
265 | url: string,
266 | },
267 | };
268 | ```
269 |
270 | In `index.tsx` file put the following code :
271 |
272 | ```js
273 | import { FlashList } from '@shopify/flash-list';
274 | import React from 'react';
275 |
276 | import CatCard from './CatCard';
277 | import { CatType } from './types';
278 |
279 | type CatsPreviewProps = {
280 | catsData: any[] | undefined | CatType[],
281 | loadMoreCats: () => void,
282 | isFetching: boolean,
283 | };
284 |
285 | const CatsPreview: React.FC = ({
286 | catsData,
287 | loadMoreCats,
288 | isFetching,
289 | }) => {
290 | return (
291 | (
294 |
295 | )}
296 | keyExtractor={item => item.id}
297 | numColumns={2}
298 | estimatedItemSize={190 * 15}
299 | refreshing={isFetching}
300 | onRefresh={loadMoreCats}
301 | onEndReached={loadMoreCats}
302 | onEndReachedThreshold={0.1}
303 | contentContainerStyle={{ paddingVertical: 12 }}
304 | />
305 | );
306 | };
307 |
308 | export default CatsPreview;
309 | ```
310 |
311 | In the above code we're accepting `catsData`, `loadMoreCats` and `isFetching` as props. To break it down `catsData` is the data that will be shown in the screen. When scroll position reaches the threshold value, a function to load new data can be called. In React Native, the threshold value ranges from 0 to 1, with 0.5 serving as the default. In above code we have used the function `loadMoreCats` which will be used to fetch cats when scrolling. FlashList provides `RefreshControl` which can be used show to a loading indicator while fetching data. To use it we need to provide two props to `FlashList`, `refreshing` and `onRefresh`. `refreshing` is boolean property and `onRefresh` is a callback function which will be called while fetching. For `refreshing` we got `isFetching` and for `onRefresh` we have `loadMoreCats`.
312 |
313 | ## Fetching Data
314 |
315 | To fetch data we will utilize a custom hook. To get started create a file `useCats.ts` inside `hooks` directory. We will be fetching data from the [Cats API](https://thecatapi.com) and will use the `useInfiniteQuery` hook from react-query. `useInfiniteQuery` hooks accepts the same arguments as `useQuery`. First one is an array of unique keys, second is a fetcher function which will fetch the data and third is an optional object with some properties.
316 |
317 | Inside `useCats.ts` file add the following code :
318 |
319 | ```js
320 | import { useInfiniteQuery } from 'react-query';
321 |
322 | const fetcher = async (pageNumber: number = 0) => {
323 | try {
324 | const response = await fetch(
325 | `https://api.thecatapi.com/v1/breeds?limit=20&page=${pageNumber}`,
326 | );
327 | const data = await response.json();
328 | return { data, nextPage: pageNumber + 1 };
329 | } catch (error) {
330 | if (error instanceof Error) throw new Error(error.message);
331 | else throw new Error('Something went wrong.');
332 | }
333 | };
334 |
335 | export default function useCats() {
336 | const {
337 | data,
338 | isError,
339 | isLoading,
340 | error,
341 | isFetching,
342 | hasNextPage,
343 | fetchNextPage,
344 | } = useInfiniteQuery(['dogs'], () => fetcher(), {
345 | getNextPageParam: ({ nextPage }) => nextPage,
346 | staleTime: Infinity,
347 | });
348 |
349 | return {
350 | data,
351 | isError,
352 | isLoading,
353 | error,
354 | isFetching,
355 | hasNextPage,
356 | fetchNextPage,
357 | };
358 | }
359 | ```
360 |
361 | In the above code the `fetcher` function accepts an argument `pageNumber` to paginate the data form the api. The returned data is also modified, which is an object containing the keys data and nextPage. Every time an API call is successful, nextPage is increased. This format of the data is required by useInfiniteQuery. The response we received from the `fetcher` method is passed as the lastPage parameter, which is accepted by getNextPageParam, which then returns the subsequent page. `useInfiniteQuery` returns several additional methods to us. There are now functions `fetchNextPage` and a boolean property `hasNextPage` which indicates if we can make more query.
362 |
363 | ## Combining everything
364 |
365 | The data format returned by `useInfiniteQuery` is an object with two keys:
366 |
367 | - pageParams - an array of the page number
368 | - pages - an array of our data for each page
369 |
370 | In order to map through the data for each page as an array and render them, we must flatten the pages first. We can use the flatMap method.
371 |
372 | ```js
373 | const catsData = data?.pages.flatMap(page => page.data);
374 | ```
375 |
376 | Open the `Cats.tsx` file inside `screens` folder and add the following code :
377 |
378 | ```js
379 | import React from 'react';
380 | import { StyleSheet, Text, View } from 'react-native';
381 |
382 | import CatsPreview from '../../components/Cats';
383 | import useCats from '../../hooks/useCats';
384 |
385 | const CatsScreen = () => {
386 | const { isError, data, error, fetchNextPage, hasNextPage, isFetching } =
387 | useCats();
388 |
389 | const catsData = data?.pages.flatMap(page => page.data);
390 | const loadMoreCats = () => hasNextPage && fetchNextPage();
391 |
392 | return (
393 |
394 | {isError && (
395 |
396 | {error instanceof Error ? error.message : 'Something went wrong'}.
397 |
398 | )}
399 |
404 |
405 | );
406 | };
407 |
408 | const styles = StyleSheet.create({
409 | container: {
410 | height: '100%',
411 | width: '100%',
412 | marginLeft: 12,
413 | },
414 | error: {
415 | color: '#ffe742',
416 | fontSize: 18,
417 | fontWeight: '600',
418 | textAlign: 'center',
419 | marginVertical: 20,
420 | },
421 | });
422 |
423 | export default CatsScreen;
424 | ```
425 |
426 | **After everything our app should look something like this :**
427 |
428 |
429 |
430 | It's kind of good but when the app first loads we get a non pleasant layout shift. To fix this lets first add a npm package `react-native-animatable` :
431 |
432 | ```bash
433 | yarn add react-native-animatable
434 | ```
435 |
436 | Now open the `CatCard.tsx` file and update with the following code :
437 |
438 | ```js
439 | import React from 'react';
440 | import { useNavigation } from '@react-navigation/native';
441 | import { View as AnimatedView } from 'react-native-animatable';
442 | import { Image, StyleSheet, Text, TouchableOpacity } from 'react-native';
443 | import { NativeStackNavigationProp } from '@react-navigation/native-stack';
444 |
445 | import { AppStackParams } from '../../../navigation/AppNavigation';
446 | import { CatType } from '../types';
447 |
448 | const CatCard: React.FC<{ item: CatType; index: number }> = ({
449 | item,
450 | index,
451 | }) => {
452 | const { image, name, origin } = item;
453 | const navigation = useNavigation>();
454 |
455 | return (
456 |
457 | navigation.navigate('CatScreen', item)}>
461 |
466 | {name}
467 | {origin}
468 |
469 |
470 | );
471 | };
472 |
473 | const styles = StyleSheet.create({
474 | container: {
475 | width: 170,
476 | padding: 12,
477 | borderRadius: 10,
478 | marginBottom: 20,
479 | backgroundColor: '#403c4a',
480 | alignItems: 'center',
481 | justifyContent: 'center',
482 | },
483 | image: {
484 | width: 70,
485 | height: 70,
486 | borderRadius: 80,
487 | },
488 | name: {
489 | color: '#f4f2fb',
490 | fontSize: 16,
491 | fontWeight: 'bold',
492 | marginTop: 10,
493 | },
494 | origin: {
495 | color: '#b1acb9',
496 | fontSize: 12,
497 | fontWeight: '600',
498 | marginBottom: 5,
499 | },
500 | });
501 |
502 | export default CatCard;
503 | ```
504 |
505 | Here I'm using `slideInUp` animation. Use can use other animation types. I'm using the index number to delay the animation of each card.
506 |
507 | Now let's add the screen to view each Cat's detailed information. We've an `onPress` handler on the **CatCard** and passing the cat data to the **CatScreen** page. Update the `Cat.tsx` file :
508 |
509 | ```js
510 | import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
511 | import { NativeStackNavigationProp } from '@react-navigation/native-stack';
512 | import React from 'react';
513 | import {
514 | Image,
515 | ImageSourcePropType,
516 | Linking,
517 | ScrollView,
518 | StyleSheet,
519 | Text,
520 | TouchableOpacity,
521 | View,
522 | } from 'react-native';
523 |
524 | import arrowLeft from '../../assets/arrow-left.png';
525 | import { AppStackParams } from '../../navigation/AppNavigation';
526 | import styles from './styles';
527 |
528 | const CatScreen = () => {
529 | const { params: cat } = useRoute>();
530 | const navigation = useNavigation>();
531 |
532 | return (
533 |
534 |
539 | navigation.goBack()}>
542 |
543 |
544 |
545 |
546 | {cat.name}
547 | {cat.origin}
548 |
549 |
550 | Description
551 | {cat.description}
552 |
553 |
554 | Temperament
555 | {cat.temperament}
556 |
557 |
558 | Life span
559 | {cat.life_span} years
560 |
561 |
562 | Scores
563 |
564 | Adaptability
565 | -
566 | {cat.adaptability}
567 |
568 |
569 | Child Friendly
570 | -
571 | {cat.child_friendly}
572 |
573 |
574 | Stranger Friendly
575 | -
576 | {cat.stranger_friendly}
577 |
578 |
579 |
580 | Wikipedia URL
581 | Linking.openURL(cat.wikipedia_url)}>
584 | {cat.wikipedia_url}
585 |
586 |
587 |
588 |
589 | );
590 | };
591 |
592 | const styles = StyleSheet.create({
593 | image: { width: '100%', height: 300 },
594 | arrowContainer: {
595 | position: 'absolute',
596 | width: 27,
597 | height: 27,
598 | padding: 7,
599 | backgroundColor: '#f4f73e',
600 | borderRadius: 50,
601 | top: 15,
602 | left: 15,
603 | },
604 | arrow: {
605 | width: '100%',
606 | height: '100%',
607 | },
608 | textContainer: { paddingBottom: 15, paddingHorizontal: 20 },
609 | name: {
610 | color: '#f5f2fc',
611 | fontSize: 35,
612 | fontWeight: '700',
613 | marginBottom: -2,
614 | },
615 | origin: { color: '#767980', fontSize: 20, fontWeight: '700' },
616 | container: {
617 | marginTop: 20,
618 | },
619 | heading: {
620 | fontWeight: '700',
621 | fontSize: 15,
622 | color: '#d4d0e0',
623 | marginBottom: 5,
624 | },
625 | text: { fontWeight: '500', fontSize: 13, color: '#767980' },
626 | flex: { flexDirection: 'row', alignItems: 'center' },
627 | mr: { marginHorizontal: 10 },
628 | });
629 |
630 | export default CatScreen;
631 | ```
632 |
633 | **If everything was okay it should look something like this :**
634 |
635 |
636 |
637 | ## Conclusion
638 |
639 | This concludes our app. I believe React Query and FlashList is more capable and will become more well-liked by the community, I believe, other developers to can give it a shot.
640 |
641 | Repo link [React Query Infinite Scroll](https://github.com/iamNilotpal/infinite-scroll)
642 |
--------------------------------------------------------------------------------
/__tests__/App-test.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * @format
3 | */
4 |
5 | import 'react-native';
6 | import React from 'react';
7 | import App from '../App';
8 |
9 | // Note: test renderer must be required after react-native.
10 | import renderer from 'react-test-renderer';
11 |
12 | it('renders correctly', () => {
13 | renderer.create();
14 | });
15 |
--------------------------------------------------------------------------------
/android/app/_BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.infinitescroll",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.infinitescroll",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 | import org.apache.tools.ant.taskdefs.condition.Os
5 |
6 | /**
7 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
8 | * and bundleReleaseJsAndAssets).
9 | * These basically call `react-native bundle` with the correct arguments during the Android build
10 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
11 | * bundle directly from the development server. Below you can see all the possible configurations
12 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
13 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
14 | *
15 | * project.ext.react = [
16 | * // the name of the generated asset file containing your JS bundle
17 | * bundleAssetName: "index.android.bundle",
18 | *
19 | * // the entry file for bundle generation. If none specified and
20 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
21 | * // default. Can be overridden with ENTRY_FILE environment variable.
22 | * entryFile: "index.android.js",
23 | *
24 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
25 | * bundleCommand: "ram-bundle",
26 | *
27 | * // whether to bundle JS and assets in debug mode
28 | * bundleInDebug: false,
29 | *
30 | * // whether to bundle JS and assets in release mode
31 | * bundleInRelease: true,
32 | *
33 | * // whether to bundle JS and assets in another build variant (if configured).
34 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
35 | * // The configuration property can be in the following formats
36 | * // 'bundleIn${productFlavor}${buildType}'
37 | * // 'bundleIn${buildType}'
38 | * // bundleInFreeDebug: true,
39 | * // bundleInPaidRelease: true,
40 | * // bundleInBeta: true,
41 | *
42 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
43 | * // for example: to disable dev mode in the staging build type (if configured)
44 | * devDisabledInStaging: true,
45 | * // The configuration property can be in the following formats
46 | * // 'devDisabledIn${productFlavor}${buildType}'
47 | * // 'devDisabledIn${buildType}'
48 | *
49 | * // the root of your project, i.e. where "package.json" lives
50 | * root: "../../",
51 | *
52 | * // where to put the JS bundle asset in debug mode
53 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
54 | *
55 | * // where to put the JS bundle asset in release mode
56 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
57 | *
58 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
59 | * // require('./image.png')), in debug mode
60 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
61 | *
62 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
63 | * // require('./image.png')), in release mode
64 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
65 | *
66 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
67 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
68 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
69 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
70 | * // for example, you might want to remove it from here.
71 | * inputExcludes: ["android/**", "ios/**"],
72 | *
73 | * // override which node gets called and with what additional arguments
74 | * nodeExecutableAndArgs: ["node"],
75 | *
76 | * // supply additional arguments to the packager
77 | * extraPackagerArgs: []
78 | * ]
79 | */
80 |
81 | project.ext.react = [
82 | enableHermes: true, // clean and rebuild if changing
83 | ]
84 |
85 | apply from: "../../node_modules/react-native/react.gradle"
86 |
87 | /**
88 | * Set this to true to create two separate APKs instead of one:
89 | * - An APK that only works on ARM devices
90 | * - An APK that only works on x86 devices
91 | * The advantage is the size of the APK is reduced by about 4MB.
92 | * Upload all the APKs to the Play Store and people will download
93 | * the correct one based on the CPU architecture of their device.
94 | */
95 | def enableSeparateBuildPerCPUArchitecture = false
96 |
97 | /**
98 | * Run Proguard to shrink the Java bytecode in release builds.
99 | */
100 | def enableProguardInReleaseBuilds = false
101 |
102 | /**
103 | * The preferred build flavor of JavaScriptCore.
104 | *
105 | * For example, to use the international variant, you can use:
106 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
107 | *
108 | * The international variant includes ICU i18n library and necessary data
109 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
110 | * give correct results when using with locales other than en-US. Note that
111 | * this variant is about 6MiB larger per architecture than default.
112 | */
113 | def jscFlavor = 'org.webkit:android-jsc:+'
114 |
115 | /**
116 | * Whether to enable the Hermes VM.
117 | *
118 | * This should be set on project.ext.react and that value will be read here. If it is not set
119 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
120 | * and the benefits of using Hermes will therefore be sharply reduced.
121 | */
122 | def enableHermes = project.ext.react.get("enableHermes", false);
123 |
124 | /**
125 | * Architectures to build native code for.
126 | */
127 | def reactNativeArchitectures() {
128 | def value = project.getProperties().get("reactNativeArchitectures")
129 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
130 | }
131 |
132 | android {
133 | ndkVersion rootProject.ext.ndkVersion
134 |
135 | compileSdkVersion rootProject.ext.compileSdkVersion
136 |
137 | defaultConfig {
138 | applicationId "com.infinitescroll"
139 | minSdkVersion rootProject.ext.minSdkVersion
140 | targetSdkVersion rootProject.ext.targetSdkVersion
141 | versionCode 1
142 | versionName "1.0"
143 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
144 |
145 | if (isNewArchitectureEnabled()) {
146 | // We configure the CMake build only if you decide to opt-in for the New Architecture.
147 | externalNativeBuild {
148 | cmake {
149 | arguments "-DPROJECT_BUILD_DIR=$buildDir",
150 | "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
151 | "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
152 | "-DNODE_MODULES_DIR=$rootDir/../node_modules",
153 | "-DANDROID_STL=c++_shared"
154 | }
155 | }
156 | if (!enableSeparateBuildPerCPUArchitecture) {
157 | ndk {
158 | abiFilters (*reactNativeArchitectures())
159 | }
160 | }
161 | }
162 | }
163 |
164 | if (isNewArchitectureEnabled()) {
165 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
166 | externalNativeBuild {
167 | cmake {
168 | path "$projectDir/src/main/jni/CMakeLists.txt"
169 | }
170 | }
171 | def reactAndroidProjectDir = project(':ReactAndroid').projectDir
172 | def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
173 | dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
174 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
175 | into("$buildDir/react-ndk/exported")
176 | }
177 | def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
178 | dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
179 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
180 | into("$buildDir/react-ndk/exported")
181 | }
182 | afterEvaluate {
183 | // If you wish to add a custom TurboModule or component locally,
184 | // you should uncomment this line.
185 | // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
186 | preDebugBuild.dependsOn(packageReactNdkDebugLibs)
187 | preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
188 |
189 | // Due to a bug inside AGP, we have to explicitly set a dependency
190 | // between configureCMakeDebug* tasks and the preBuild tasks.
191 | // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
192 | configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
193 | configureCMakeDebug.dependsOn(preDebugBuild)
194 | reactNativeArchitectures().each { architecture ->
195 | tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
196 | dependsOn("preDebugBuild")
197 | }
198 | tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
199 | dependsOn("preReleaseBuild")
200 | }
201 | }
202 | }
203 | }
204 |
205 | splits {
206 | abi {
207 | reset()
208 | enable enableSeparateBuildPerCPUArchitecture
209 | universalApk false // If true, also generate a universal APK
210 | include (*reactNativeArchitectures())
211 | }
212 | }
213 | signingConfigs {
214 | debug {
215 | storeFile file('debug.keystore')
216 | storePassword 'android'
217 | keyAlias 'androiddebugkey'
218 | keyPassword 'android'
219 | }
220 | }
221 | buildTypes {
222 | debug {
223 | signingConfig signingConfigs.debug
224 | }
225 | release {
226 | // Caution! In production, you need to generate your own keystore file.
227 | // see https://reactnative.dev/docs/signed-apk-android.
228 | signingConfig signingConfigs.debug
229 | minifyEnabled enableProguardInReleaseBuilds
230 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
231 | }
232 | }
233 |
234 | // applicationVariants are e.g. debug, release
235 | applicationVariants.all { variant ->
236 | variant.outputs.each { output ->
237 | // For each separate APK per architecture, set a unique version code as described here:
238 | // https://developer.android.com/studio/build/configure-apk-splits.html
239 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
240 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
241 | def abi = output.getFilter(OutputFile.ABI)
242 | if (abi != null) { // null for the universal-debug, universal-release variants
243 | output.versionCodeOverride =
244 | defaultConfig.versionCode * 1000 + versionCodes.get(abi)
245 | }
246 |
247 | }
248 | }
249 | }
250 |
251 | dependencies {
252 | implementation fileTree(dir: "libs", include: ["*.jar"])
253 |
254 | //noinspection GradleDynamicVersion
255 | implementation "com.facebook.react:react-native:+" // From node_modules
256 |
257 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
258 |
259 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
260 | exclude group:'com.facebook.fbjni'
261 | }
262 |
263 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
264 | exclude group:'com.facebook.flipper'
265 | exclude group:'com.squareup.okhttp3', module:'okhttp'
266 | }
267 |
268 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
269 | exclude group:'com.facebook.flipper'
270 | }
271 |
272 | if (enableHermes) {
273 | //noinspection GradleDynamicVersion
274 | implementation("com.facebook.react:hermes-engine:+") { // From node_modules
275 | exclude group:'com.facebook.fbjni'
276 | }
277 | } else {
278 | implementation jscFlavor
279 | }
280 | }
281 |
282 | if (isNewArchitectureEnabled()) {
283 | // If new architecture is enabled, we let you build RN from source
284 | // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
285 | // This will be applied to all the imported transtitive dependency.
286 | configurations.all {
287 | resolutionStrategy.dependencySubstitution {
288 | substitute(module("com.facebook.react:react-native"))
289 | .using(project(":ReactAndroid"))
290 | .because("On New Architecture we're building React Native from source")
291 | substitute(module("com.facebook.react:hermes-engine"))
292 | .using(project(":ReactAndroid:hermes-engine"))
293 | .because("On New Architecture we're building Hermes from source")
294 | }
295 | }
296 | }
297 |
298 | // Run this once to be able to run the application with BUCK
299 | // puts all compile dependencies into folder libs for BUCK to use
300 | task copyDownloadableDepsToLibs(type: Copy) {
301 | from configurations.implementation
302 | into 'libs'
303 | }
304 |
305 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
306 |
307 | def isNewArchitectureEnabled() {
308 | // To opt-in for the New Architecture, you can either:
309 | // - Set `newArchEnabled` to true inside the `gradle.properties` file
310 | // - Invoke gradle with `-newArchEnabled=true`
311 | // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
312 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
313 | }
314 |
--------------------------------------------------------------------------------
/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/iamNilotpal/infinite-scroll/600467a0e0273aa7a4865ca6d26c81b69b3a0456/android/app/debug.keystore
--------------------------------------------------------------------------------
/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/android/app/src/debug/java/com/infinitescroll/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | *
This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.infinitescroll;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceEventListener;
23 | import com.facebook.react.ReactInstanceManager;
24 | import com.facebook.react.bridge.ReactContext;
25 | import com.facebook.react.modules.network.NetworkingModule;
26 | import okhttp3.OkHttpClient;
27 |
28 | public class ReactNativeFlipper {
29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
30 | if (FlipperUtils.shouldEnableFlipper(context)) {
31 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
32 |
33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
34 | client.addPlugin(new ReactFlipperPlugin());
35 | client.addPlugin(new DatabasesFlipperPlugin(context));
36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
37 | client.addPlugin(CrashReporterPlugin.getInstance());
38 |
39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
40 | NetworkingModule.setCustomClientBuilder(
41 | new NetworkingModule.CustomClientBuilder() {
42 | @Override
43 | public void apply(OkHttpClient.Builder builder) {
44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
45 | }
46 | });
47 | client.addPlugin(networkFlipperPlugin);
48 | client.start();
49 |
50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
51 | // Hence we run if after all native modules have been initialized
52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
53 | if (reactContext == null) {
54 | reactInstanceManager.addReactInstanceEventListener(
55 | new ReactInstanceEventListener() {
56 | @Override
57 | public void onReactContextInitialized(ReactContext reactContext) {
58 | reactInstanceManager.removeReactInstanceEventListener(this);
59 | reactContext.runOnNativeModulesQueueThread(
60 | new Runnable() {
61 | @Override
62 | public void run() {
63 | client.addPlugin(new FrescoFlipperPlugin());
64 | }
65 | });
66 | }
67 | });
68 | } else {
69 | client.addPlugin(new FrescoFlipperPlugin());
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/infinitescroll/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.infinitescroll;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.ReactRootView;
6 |
7 | public class MainActivity extends ReactActivity {
8 |
9 | /**
10 | * Returns the name of the main component registered from JavaScript. This is used to schedule
11 | * rendering of the component.
12 | */
13 | @Override
14 | protected String getMainComponentName() {
15 | return "InfiniteScroll";
16 | }
17 |
18 | /**
19 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
20 | * you can specify the renderer you wish to use - the new renderer (Fabric) or the old renderer
21 | * (Paper).
22 | */
23 | @Override
24 | protected ReactActivityDelegate createReactActivityDelegate() {
25 | return new MainActivityDelegate(this, getMainComponentName());
26 | }
27 |
28 | public static class MainActivityDelegate extends ReactActivityDelegate {
29 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
30 | super(activity, mainComponentName);
31 | }
32 |
33 | @Override
34 | protected ReactRootView createRootView() {
35 | ReactRootView reactRootView = new ReactRootView(getContext());
36 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
37 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
38 | return reactRootView;
39 | }
40 |
41 | @Override
42 | protected boolean isConcurrentRootEnabled() {
43 | // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
44 | // More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
45 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/infinitescroll/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.infinitescroll;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactApplication;
7 | import com.facebook.react.ReactInstanceManager;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.config.ReactFeatureFlags;
11 | import com.facebook.soloader.SoLoader;
12 | import com.infinitescroll.newarchitecture.MainApplicationReactNativeHost;
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.util.List;
15 |
16 | public class MainApplication extends Application implements ReactApplication {
17 |
18 | private final ReactNativeHost mReactNativeHost =
19 | new ReactNativeHost(this) {
20 | @Override
21 | public boolean getUseDeveloperSupport() {
22 | return BuildConfig.DEBUG;
23 | }
24 |
25 | @Override
26 | protected List getPackages() {
27 | @SuppressWarnings("UnnecessaryLocalVariable")
28 | List packages = new PackageList(this).getPackages();
29 | // Packages that cannot be autolinked yet can be added manually here, for example:
30 | // packages.add(new MyReactNativePackage());
31 | return packages;
32 | }
33 |
34 | @Override
35 | protected String getJSMainModuleName() {
36 | return "index";
37 | }
38 | };
39 |
40 | private final ReactNativeHost mNewArchitectureNativeHost =
41 | new MainApplicationReactNativeHost(this);
42 |
43 | @Override
44 | public ReactNativeHost getReactNativeHost() {
45 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
46 | return mNewArchitectureNativeHost;
47 | } else {
48 | return mReactNativeHost;
49 | }
50 | }
51 |
52 | @Override
53 | public void onCreate() {
54 | super.onCreate();
55 | // If you opted-in for the New Architecture, we enable the TurboModule system
56 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
57 | SoLoader.init(this, /* native exopackage */ false);
58 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
59 | }
60 |
61 | /**
62 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
63 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
64 | *
65 | * @param context
66 | * @param reactInstanceManager
67 | */
68 | private static void initializeFlipper(
69 | Context context, ReactInstanceManager reactInstanceManager) {
70 | if (BuildConfig.DEBUG) {
71 | try {
72 | /*
73 | We use reflection here to pick up the class that initializes Flipper,
74 | since Flipper library is not available in release mode
75 | */
76 | Class> aClass = Class.forName("com.infinitescroll.ReactNativeFlipper");
77 | aClass
78 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
79 | .invoke(null, context, reactInstanceManager);
80 | } catch (ClassNotFoundException e) {
81 | e.printStackTrace();
82 | } catch (NoSuchMethodException e) {
83 | e.printStackTrace();
84 | } catch (IllegalAccessException e) {
85 | e.printStackTrace();
86 | } catch (InvocationTargetException e) {
87 | e.printStackTrace();
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/infinitescroll/newarchitecture/MainApplicationReactNativeHost.java:
--------------------------------------------------------------------------------
1 | package com.infinitescroll.newarchitecture;
2 |
3 | import android.app.Application;
4 | import androidx.annotation.NonNull;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactInstanceManager;
7 | import com.facebook.react.ReactNativeHost;
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
10 | import com.facebook.react.bridge.JSIModulePackage;
11 | import com.facebook.react.bridge.JSIModuleProvider;
12 | import com.facebook.react.bridge.JSIModuleSpec;
13 | import com.facebook.react.bridge.JSIModuleType;
14 | import com.facebook.react.bridge.JavaScriptContextHolder;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.UIManager;
17 | import com.facebook.react.fabric.ComponentFactory;
18 | import com.facebook.react.fabric.CoreComponentsRegistry;
19 | import com.facebook.react.fabric.FabricJSIModuleProvider;
20 | import com.facebook.react.fabric.ReactNativeConfig;
21 | import com.facebook.react.uimanager.ViewManagerRegistry;
22 | import com.infinitescroll.BuildConfig;
23 | import com.infinitescroll.newarchitecture.components.MainComponentsRegistry;
24 | import com.infinitescroll.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | /**
29 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both
30 | * TurboModule delegates and the Fabric Renderer.
31 | *
32 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
33 | * `newArchEnabled` property). Is ignored otherwise.
34 | */
35 | public class MainApplicationReactNativeHost extends ReactNativeHost {
36 | public MainApplicationReactNativeHost(Application application) {
37 | super(application);
38 | }
39 |
40 | @Override
41 | public boolean getUseDeveloperSupport() {
42 | return BuildConfig.DEBUG;
43 | }
44 |
45 | @Override
46 | protected List getPackages() {
47 | List packages = new PackageList(this).getPackages();
48 | // Packages that cannot be autolinked yet can be added manually here, for example:
49 | // packages.add(new MyReactNativePackage());
50 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
51 | // packages.add(new TurboReactPackage() { ... });
52 | // If you have custom Fabric Components, their ViewManagers should also be loaded here
53 | // inside a ReactPackage.
54 | return packages;
55 | }
56 |
57 | @Override
58 | protected String getJSMainModuleName() {
59 | return "index";
60 | }
61 |
62 | @NonNull
63 | @Override
64 | protected ReactPackageTurboModuleManagerDelegate.Builder
65 | getReactPackageTurboModuleManagerDelegateBuilder() {
66 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary
67 | // for the new architecture and to use TurboModules correctly.
68 | return new MainApplicationTurboModuleManagerDelegate.Builder();
69 | }
70 |
71 | @Override
72 | protected JSIModulePackage getJSIModulePackage() {
73 | return new JSIModulePackage() {
74 | @Override
75 | public List getJSIModules(
76 | final ReactApplicationContext reactApplicationContext,
77 | final JavaScriptContextHolder jsContext) {
78 | final List specs = new ArrayList<>();
79 |
80 | // Here we provide a new JSIModuleSpec that will be responsible of providing the
81 | // custom Fabric Components.
82 | specs.add(
83 | new JSIModuleSpec() {
84 | @Override
85 | public JSIModuleType getJSIModuleType() {
86 | return JSIModuleType.UIManager;
87 | }
88 |
89 | @Override
90 | public JSIModuleProvider getJSIModuleProvider() {
91 | final ComponentFactory componentFactory = new ComponentFactory();
92 | CoreComponentsRegistry.register(componentFactory);
93 |
94 | // Here we register a Components Registry.
95 | // The one that is generated with the template contains no components
96 | // and just provides you the one from React Native core.
97 | MainComponentsRegistry.register(componentFactory);
98 |
99 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
100 |
101 | ViewManagerRegistry viewManagerRegistry =
102 | new ViewManagerRegistry(
103 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
104 |
105 | return new FabricJSIModuleProvider(
106 | reactApplicationContext,
107 | componentFactory,
108 | ReactNativeConfig.DEFAULT_CONFIG,
109 | viewManagerRegistry);
110 | }
111 | });
112 | return specs;
113 | }
114 | };
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/infinitescroll/newarchitecture/components/MainComponentsRegistry.java:
--------------------------------------------------------------------------------
1 | package com.infinitescroll.newarchitecture.components;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.proguard.annotations.DoNotStrip;
5 | import com.facebook.react.fabric.ComponentFactory;
6 | import com.facebook.soloader.SoLoader;
7 |
8 | /**
9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a
10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
11 | * folder for you).
12 | *
13 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
14 | * `newArchEnabled` property). Is ignored otherwise.
15 | */
16 | @DoNotStrip
17 | public class MainComponentsRegistry {
18 | static {
19 | SoLoader.loadLibrary("fabricjni");
20 | }
21 |
22 | @DoNotStrip private final HybridData mHybridData;
23 |
24 | @DoNotStrip
25 | private native HybridData initHybrid(ComponentFactory componentFactory);
26 |
27 | @DoNotStrip
28 | private MainComponentsRegistry(ComponentFactory componentFactory) {
29 | mHybridData = initHybrid(componentFactory);
30 | }
31 |
32 | @DoNotStrip
33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) {
34 | return new MainComponentsRegistry(componentFactory);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/android/app/src/main/java/com/infinitescroll/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package com.infinitescroll.newarchitecture.modules;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.soloader.SoLoader;
8 | import java.util.List;
9 |
10 | /**
11 | * Class responsible to load the TurboModules. This class has native methods and needs a
12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
13 | * folder for you).
14 | *
15 | *