There are several ways to load the contents of a text file that is either bundled with your React project or hosted separately.
- Put the file in the public folder and fetch it via direct URL.
- Import the file which will use Webpack's general asset module to bundle and emit a URL you can load.
- Host the file somewhere on the public internet on a server configured with CORS access. AWS S3 for example
Both approaches involve loading a URL. You could make a generic function to do so...
const loadTextFile = async (url) => {
const res = await fetch(url);
if (!res.ok) {
throw res;
}
return res.text();
};
and then load the content into a state value, eg
const [word, setWord] = useState("");
Option #1 - public folder
useEffect(() => {
loadTextFile(process.env.PUBLIC_URL + "/word.txt")
.then(setWord)
.catch(console.error);
}, []);
Option #2 - asset
import fileUrl from "./path/to/word.txt";
// ...
useEffect(() => {
loadTextFile(fileUrl)
.then(setWord)
.catch(console.error);
}, []);
Option #3 - online
useEffect(() => {
loadTextFile("https://example.com/word.txt")
.then(setWord)
.catch(console.error);
}, []);

Bonus round - custom webpack config
Customise your Webpack config to add a resource query to load modules using source assets
module: {
rules: [
// ...
{
resourceQuery: /raw/,
type: 'asset/source',
}
]
},
and import your text file contents using
import word from "./path/to/word.txt?raw";
If you're using create-react-app
, this will require ejecting your configuration.
The JSON option
If you don't mind encoding your text file content into a JSON string literal, you can always use a .json
file.
For example, assets/word.json
"this is some plain text in a JSON file"
import jsonFileContents from "./assets/word.json";