A few reasons why I might do this:
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With