3

Issue details

  1. .env value not initialized in the react property
  2. siteKey value is always blank

Property in react

const [siteKey] = useState(process.env.REACT_CAPTCHA_SITE_KEY);

Key in .env

REACT_CAPTCHA_SITE_KEY='some key'

Html

<ReCAPTCHA sitekey={siteKey}/>
Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • You don't need to use a hook here because you don't use a setter. Can you try with a basic `const siteKey = process.env.REACT_CAPTCHA_SITE_KEY` ? – Raphael Escrig Nov 03 '22 at 17:22
  • 2
    are you using create-react-app? if so, the env variables should be prefixed by `REACT_APP` – nullptr Nov 08 '22 at 05:12

3 Answers3

3

Main issue is with your environment declaration, as per create-react-app:

You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

As you don't have any setter method needed for useState, you can define your variable just with const, like:

const siteKey = process.env.REACT_APP_CAPTCHA_SITE_KEY
Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
1

I saw Some Issue in your code, First thing is,UseState hook initialization is wrong. It Should be,

  const [siteKey, setsiteKey] = useState(process.env.REACT_APP_CAPTCHA_SITE_KEY);

And also You don't need to use this environment variable as useState, because it is not changing so, when you need to access environment variable, use as below,

ex:const siteKey=process.env.REACT_APP_CAPTCHA_SITE_KEY;

Other Important Issues are,

Your environment variable should prefix with the REACT_APP_ in the .env file. ex:process.env.REACT_APP_SOME_VARIABLE

And possible Issue can be, your .env file is not in your root which is that, within the same directory as the package. json file.

  • 1
    I don't find any issue with `useState`, we are allowed to use `useState` without setter method. – Harsh Patel Nov 14 '22 at 06:40
  • 1
    @HarshPatel please read the answer before the commenting. There are no point to have a useState for having environment variable values. since it is not changing, it is constant for the project. – Lakruwan Pathirage Nov 14 '22 at 06:51
0

Key in .env should be like as shown below

REACT_APP_CAPTCHA_SITE_KEY=some_key_value

Also whenever you edit your .env file you need to restart your React app to take effect of your modified file.

Bahubali Ak
  • 181
  • 3
  • 13