A modern Reactjs app can be consisting of multiple components, connection to different databases, APIs etc. In other Nodejs projects we can use the dotenv package to store configuration details and can access with process.env.
Is dotenv useful for Reactjs ? Yeh.
Suppose you have using an API in many of the components and wanna some correction in API path, may be a change in basic URL. What we do ? Go through all of the component and change the base URL. Tiresome job !
For such case place the URL in .env (/src) file and use the process.env.REACT_APP_API_SERVER in all of the component. Yo need to change only the .env file for updating base URL.
First up all install the package using
npm i dotenv
and in the App.js , require the package as follows and use it in the component
.... require("dotenv").config();
.get(`${process.env.REACT_APP_API_SERVER}/post/find`) .then((response) => { if (response.data.length > 0) { this.setState({ posts: response.data, }); } }) .catch((error) => { console.log(error); });