Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React Native how do you bundle a text file and read it's value at runtime?

A few reasons why I might do this:

  • To create some webviews and inject javascript loaded from files
  • To separate large chunks of text into separate files rather than forcing them into views
  • To include raw data of an arbitrary format (eg, CSV) to be used in the app

In React Native you can use require to import an image file, but as far as I've seen, this only works for image files. And it (strangely) also works for JSON files (see Importing Text from local json file in React native). However, I haven't seen anywhere talking about importing plain old text files.

like image 314
eremzeit Avatar asked May 19 '16 08:05

eremzeit


People also ask

How do you read data from a TXT file in React?

To read a text file in React, we can use the FileReader constructor. to define the showFile function that gets the selected file from e. target.

How bundle works in React Native?

Bundling. Most React apps will have their files “bundled” using tools like Webpack, Rollup or Browserify. Bundling is the process of following imported files and merging them into a single file: a “bundle”. This bundle can then be included on a webpage to load an entire app at once.


1 Answers

After looking and asking around, the best I can come up with is to use a fork of the react-native-fs library to access android "assets". This fork is a pull request out and as soon as it gets merged you can use it.

Note that in android dev, "assets" specifically refer to accessing the raw contents of a file. In order to do this sort of thing on the react native side, you need to write a native module to interface with react, hence the library above. See here (and search for assets).

In your react native project, make a file called something like android/app/src/main/assets/text.txt. Using the version of react-native-fs mentioned above, you do:

RNFS.readFileAssets('test.txt').then((res) => {   console.log('read file res: ', res); }) 

update: If you want the pull request that would enable this ability to go through, you should go let the author know you want it by giving it a thumbs up on github.

like image 186
eremzeit Avatar answered Sep 23 '22 07:09

eremzeit