Search code examples
reactjsdotenv

Issue while trying to initialize the react property


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} />

Solution

  • 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.