简体   繁体   中英

Calling data from js file to react component

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

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() 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM