Calling data from js file to react component

1.5k Views Asked by At

I have a js file with some data on my src/assets folder. I need to call that data into my react component to display it in a chart from PLotly.js

I have tried calling the data but I keep getting an error saying that the path can not be found. Should I turn it into a json file?

My data file :

{
    "data":[
      {
        "x": [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560,],
        "y": [-11.98752097, -11.98587175, -11.9840901,  -11.98657347, -11.98618678, -11.98618678],
        "type": "scatter",
        "name":"logResPerm",
        "mode": "lines+markers",
        "marker": "{color:'red'}",
      },
    ]
}

react component:

export const ScatterChart= () => { 
    return (
        <Plot {data.map((data,key)=>{
            return(
                {data}
            )
        })}/>
    )
}
1

There are 1 best solutions below

0
On

write it as variable and export it

 export const chartData = {
            "data":[
              {
                "x": [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560,],
                "y": [-11.98752097, -11.98587175, -11.9840901,  -11.98657347, -11.98618678, -11.98618678],
                "type": "scatter",
                "name":"logResPerm",
                "mode": "lines+markers",
                "marker": "{color:'red'}",
              },
            ]
        }

in your component you need to import it

import { chartData } from 'path/to/file'

export const ScatterChart = () => { 
    ... do code here, like chartData.data.map() 
}