14

const ListItem = React.createClass({
  render: function() {
    return <li > {
      this.props.item
    } < /li>;
  }
});

const ToDoList = React.createClass({
  render: function() {

    const todoItems = this.props.items.map(item => {
      return <ListItem item = {
        item
      } > < /ListItem>
    })

    return ( <
      ul > {
        todoItems
      } < /ul>
    );
  }
});

//creating a basic component with no data, just a render function
const MyApp = React.createClass({
  render: function() {
    return ( <
      div className = "well" >
      <
      h1 > Hello < /h1> <
      ToDoList > < /ToDoList> <
      /div>
    );
  }
});

//insert the component into the DOM
ReactDOM.render( < MyApp / > , document.getElementById('container'));



<
div id = "container" > < /div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

A ReactJs tutorial says:

If we want to make this a truly extensible list, we could create an array of items, then pass them into props through the ToDoList component, then render out each item. Let's do that now.

How can I pass the array of items in the above code?

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
DarkArtistry
  • 434
  • 1
  • 6
  • 22

2 Answers2

36

Data can be passed to components via props.

https://facebook.github.io/react/tutorial/tutorial.html#passing-data-through-props

In your case props would be accessed inside the components via this.props.

<TodoList /> takes a prop called items which is an array. Inside <TodoList /> you can map through that array and return elements.

For example in the render method of your class you would return TodoList with a prop of items:

const myItems = [{ name: 'item 1' }, { name: 'item2' }];
function MyApp() {
    return (
       <TodoList items={myItems} />
    );
}

Then in TodoList you map the items

function TodoList({ items }) {
    return items.map(item => (
        <h1>{item.name}</h1>
    ));
}
pizzarob
  • 11,711
  • 6
  • 48
  • 69
  • This code makes me understand how i can manupulate it with objects ,, nice :D – DarkArtistry May 13 '17 at 03:26
  • 2
    Can you please explain why we have to put curly brackets around `items` in `TodoList` function? I tried `function TodoList( items )` but it returned errors : *items.map is not a function* – Chau Pham Dec 23 '18 at 06:50
  • 1
    @Catbuilts That's just the React/Babel syntax – Pim Mar 09 '19 at 23:19
1

You just set up an attribute, with the same name

<ToDoList items={myitems} />
Gratus D.
  • 787
  • 7
  • 22