Wednesday, November 10, 2021

How React component pass data around

For React components, the basic way to receive data is passing them as component attributes when creating the component in its parent's html render method. Those attributes will pass into the component's js file as props parameter.

Within the component js file's render method, internal data can be handled by useState hook, which update the user input into component state, which leads to update the ui.

In case when a react component needs to pass data out to its parent, the parent can pass a callback method to the component as a component attribute, then when some event happens, the component can call the callback method and pass the data as callback parameter. Then the parent component can use the callback method's implementation to handle the data specified in the callback method's parameters. For example, the parent can update its own data managed by the useState hook. 

To avoid passing property value from top to low layer components, react application can use useContext to facilitate passing data directly from top component to lower layer components.


Saturday, November 6, 2021

Using custom .env file for react project

By default, react project supports .env, .env.development, .env.production and .evn.test for different build and test scenario. However, sometimes, you may need additional testing and deployment configuration with custom env file. The following steps can be used to setup custom react env files:

1. run below command to add env-cmd package to your react project

npm install env-cmd

2. create your custom env file, for example, .evn.staging in your project in the same folder as other .env files. Then add the environment variables and values in the file in the same way as other .env file.

3. in the project's package.json file's script section, add "env-cmd -f YourCustomEnvFileName" parameter before other command parameter to indicate which .env file should be used for the command, for example:

 "start": "env-cmd -f .env.staging react-scripts start", 

will start the react app by using the configuration in evn.staging file.