In ReactJS, environment variables are like secret codes that help keep sensitive information safe in our apps. Imagine having a hidden box where you store important keys or IDs. That’s what environment variables do for us. When we use Create React App (CRA) to build our app, it automatically replaces these secret codes with the real values. For example, we have %REACT_APP_PAYPAL_CLIENT_ID% in our code, and CRA will swap it with the actual PayPal client ID we’ve set in a special environment file. This way, we protect sensitive data and use the right values when needed. It’s like magic!
Environment variable setup: In your project’s root directory, you have a file named .env or .env.development (for development environment). Inside this file, you define the environment variable with the prefix REACT_APP_, like this:
REACT_APP_PAYPAL_CLIENT_ID=your_actual_paypal_client_id
CRA build process: When you run the npm start or npm build command, Create React App processes your code, including the HTML files. During this process, CRA scans your code for references to process.env.REACT_APP_VARIABLE_NAME and replaces them with the values you have specified in the environment file. In this case, it replaces %REACT_APP_PAYPAL_CLIENT_ID% in the index.html file with the value of REACT_APP_PAYPAL_CLIENT_ID from the environment file.
Resulting HTML: After the build process, the final index.html file will have the following line:
src="https://www.paypal.com/sdk/js?client-id=your_actual_paypal_client_id¤cy=USD"
So, the %REACT_APP_PAYPAL_CLIENT_ID% placeholder is dynamically replaced with the actual value of REACT_APP_PAYPAL_CLIENT_ID specified in the environment file. This is how the correct PayPal client ID gets injected into the index.html file, allowing your React application to use the correct client ID when interacting with PayPal’s SDK.