Home > OS >  What is causing difficulty when I am parsing JSON in react? White screen result
What is causing difficulty when I am parsing JSON in react? White screen result

Time:04-15

I realise this is likely a very beginner problem but I cant understand what is going wrong here I have simplified the problem to this, I am trying to write a basic app that stores calculators and their values so that I can work on several different calculators at once, here is my basic code in the react .jsx file

function CalcParse(){
    let calculators = require('./Calcs.json')
        .JSON.parse
        .calcs;

    return(
    <div>
        {calculators.map(calc => <p key={calc.name}>{calc.name}</p>)}   
    </div>
        
    )
}

and my .JSON file is

{   "calcs":[
    {
        "name":"Extended Surface Rod",
        "args":"h, k, D"
    },
    {
        "name":"Default Calculator",
        "args":"A,B"
    }]
}

and then my index.js file is

import ReactDOM from 'react-dom';
import React from 'react';
import CalcParse from './CalcParse.jsx'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
    <CalcParse/>
  </React.StrictMode>
);

annoyingly my code compiles fine but it comes back with a white screem

CodePudding user response:

You can use json file directly by require.

function CalcParse(){
    let calculators = require('./Calcs.json');

    return(
    <div>
        {calculators.calcs.map(calc => <p key={calc.name}>{calc.name}</p>)}   
    </div>
        
    )
}

The better way is:

import calculators from './Calcs.json';

// ...

function CalcParse(){
    return (
    <div>
        {calculators.calcs.map(calc => <p key={calc.name}>{calc.name}</p>)}   
    </div>

    )
}

  • Related