Reputation: 631
I'm following a tutorial on React.js, making a Todo app as an example.
App.js
import React, { Component } from 'react';
import TodoItem from "./components/TodoItem";
import Data from "./Data";
class App extends Component {
constructor(){
super();
this.state = { todos:[Data] }
}
render() {
const TodoItems = this.state.todos.map(item =>
<TodoItem key={item.id} item={item} />)
return (
<div>
{todoItems}
</div>
)
}
}
export default App;
TodoItem.js
import React from 'react';
function TodoItem (props) {
return (
<div>
<input type="checkbox" checked={props.item.completed} />
<p>{props.item.text}</p>
</div>
)
}
export default TodoItem;
Data.js is simply just an array
const Data = [{id: 1, text: "Some random text", completed: true}, //and so on... ]
When I run this, the browser only renders a checkbox, nothing else. Is there something I'm missing? I checked the dev tools by chrome and saw there are props being passed.
Upvotes: 1
Views: 85
Reputation: 30957
The problem is this: this.state = { todos:[Data] }
That doesn't put the contents of Data
in todos
, like I think you intend to do, it makes todos
an array containing Data
, which itself is an array, i.e:
todos = [ [ {id: 1, text: "Some random text", completed: true}, ... ] ]
So when you map over this.state.todos
, the 'item
' you pull out is actually the single item within todos
which is in fact the whole Data
array! (not the items within Data
like you want)
The array has no text
property, so no text shows. It also of course has no completed
property, but the checkbox does not need that property to exist to get rendered, so you just see one, single, checkbox with no text.
Change it to this, and it should work.
this.state = { todos: Data }
An unrelated thing, sure just a copy/paste typo in the code here, but just for completeness, you have const TodoItems = ...
but then reference {todoItems}
in the JSX. I guess that should be const todoItems = ...
.
Upvotes: 3
Reputation: 754
First and the foremost thing is that, you need to export data from the Data.js
file. Secondly, how you have shown your Data
variable, i'm assuming it is an array and thus you can set it directly in the state without encapsulating it in squared brackets.
I have also updated the TodoItem
to make sure the text is inline with the checkbox.
Check out the code sandbox link below!
Upvotes: -1