How do I pass parameters to react?

Viewed 4954

I'm trying to pass a parameter to my react project. I set it up with create-react-app.

I set up package.json like so:

  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --open --mode development",
    "build": "webpack --mode production"
  },

index.js:

console.log(process.argv)

I start it up and pass in my parameter:

yarn start --serverPort=3531

But then process.argv is just an empty array. How can I pass parameters to the react app?

1 Answers

What we actually want is to define an Environment Variable that our React instance can reach from within that environment, and here ours is NodeJS

What we are doing here: yarn start --serverPort=3531, is that we are passing the yarn command a parameter serverPort with the value of 3531.

While what we should do is to declare an Environment Variable such as PORT, then reach it with the help of process.env which will allow us access the current used environment.

Note that: "By convention, environment variables should have UPPER CASE names."

We change our start script in package.json to fit with the above:

PORT=3000 && webpack-dev-server --open --mode development

You can then access its value via: process.env.PORT // output --> 3000.

This is a quick workaround, but, I suggest you read more about setting up environment variables. as in CRA docs.

Related