skip to Main Content

If I have a value in my appSettings.json file…something like this:

  "AccessControl": {
    "SystemGated": "True"
  },

How can I test that value inside my React component? I am imaging something like this:

export function accessIsGated(value) {
    if (value = "True") {
        return true;
    };
    return false;
}

But I am not sure how I can access that value in my appSettings.json file…

2

Answers


  1. As i understand you’re trying to access an internal json file by importing it in your React component, i’ll leave you an example with a simple component example:

    import data from "../data.json"
            
            export default function Index() {
              console.log(data)
              
              return (
                <div>
                  {data.AccessControl.SystemGated}
                </div>
              );
            }
    
    Login or Signup to reply.
  2. Below is very simplified example of a React component, which fetches a JSON file and puts it into state for further use:

    function MyApp() {
      const [config, setConfig] = React.useState(undefined);
      
      React.useEffect(() => {
        fetch('https:/my.app.com/appSettings.json')
          .then(response => response.json())
          .then(data => setConfig(data));
      }, []);
      
      return (
        <div>
          {config ? JSON.stringify(config) : 'Fetching...'}
        </div>
      );
    }
    

    It displays it on the screen, but you can of course do whatever with it, including but not limited to: using it directly, passing it down to children, putting it in a Context to avoid prop-drilling and so on.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search