0

I'm new to react.And I'm trying to load data file to a state array instead of directly placing array of data in the state.Below I've placed the code.But this doesn't display the data.

App.js

import React, { Component } from 'react';
import Projects from './Components/Projects';
import data from './data/data'

class App extends Component {

constructor(){
  super();
  this.state = {

    myArrays: [{data}]

  }
}


render() {
 return (
    <div className="App">

    <Projects myArrays = {this.state.myArrays} />

  </div>
);
 }
 }

export default App;

It works if I replace

<Projects myArrays = {this.state.myArrays} /> with <Projects myArrays = {data} />  

What is the difference between doing this two? And why doesn't it load data with

 <Projects myArrays = {this.state.myArrays} />

Project.js

import React, { Component } from 'react';
class Projects extends Component {

render() {
let projectItems;

  projectItems = this.props.myArrays.map((project,i) =>{
    return(
    <li key = {i}>{project.title}</li>
  );
  });

  return (
  <ul>
  {projectItems}

  </ul>
  );
  }
 }

 export default Projects;

data.js

export default [
    {

    title: "Obama set for first political event since leaving office",
    category: "politics"
  },
  {

    title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
    category: "sports"
  },
  {

    title: "Virtu Financial closes KCG's European prop trading business",
    category: "business"
  }
]

1 Answer 1

1

The difference between

<Projects myArrays = {this.state.myArrays} /> 

and

<Projects myArrays = {data} />  

is the way you are assigning data to the state

this.state = {

    myArrays: [{data}]

  }

This will result in this.state.myArrays which looks like

[{data: [
    {

    title: "Obama set for first political event since leaving office",
    category: "politics"
  },
  {

    title: 'La Liga refuse to accept PSG payment for Barcelona striker Neymar',
    category: "sports"
  },
  {

    title: "Virtu Financial closes KCG's European prop trading business",
    category: "business"
  }
]
}]

Replace it with

 this.state = {

    myArrays: data

  }

and your first version will also work

Sign up to request clarification or add additional context in comments.

1 Comment

Consider Accepting the answer if it helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.