Search code examples
javascriptarraysreactjsecmascript-5webpack-4

How to access Object array file into react component?


I am trying to access an object array file within src folder eg: data.js(Object array only) this file into my app.js(react component)

in first scenario 1.I have tried this problem using react in

src--[app.js(component)/data.js(object array)].

When I was run it shows me an error like

(TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function)means null array/undefined.

in second scenarios 2. when I add object array in app.js within the same page its shows me perfect result. without an error but trying from another file like data.js it taking null array I have used to stringify() and JSON parser but no result

Object array file data.js ->

const datas=[
    {
    "id":"1",
    "firstname":"sam",
    "lastname":"parkar"
    },
    {
    "id":"2",
    "firstname":"julee",
    "lastname":"fransic"
    }
    ];

react component app.js ->

import React from 'react';
import  datas from './data';
import  DataInfo from './DataInfo';
function App () {
 const appdata=datas.map( inner => inner.id + inner.firstname + inner.lastname)
//print on console
 console.log(appdata)
    return (
     <div className="App">
           <p>App js page</p>

              {appdata} 

      </div>
    )
  }
export default App;

error ->

TypeError: _data__WEBPACK_IMPORTED_MODULE_1___default.a.map is not a function
  21 | return (  
  22 |   
  23 |   
> 24 |   <div className="App">  
     |  ^  25 |   
  26 |        <p>App js page</p>  

actual result:-
App js page

1samparkar2juleefransic
and on console (2) ["1samparkar", "2juleefransic"] 0: "1samparkar" 1: "2juleefransic"


Solution

  • Make sure you export the datas correctly

    export const datas=[
      {
        "id": "1",
        "firstname": "sam",
        "lastname": "parkar"
      },
      {
        "id": "2",
        "firstname": "julee",
        "lastname": "fransic"
      }
    ];
    

    And in app.js call it like this:

    import  {datas} from './data';