This post is continuation on my previous post -
If you have not see it, i ll suggest to go over it first, that will give you basic understanding on React.
In this post we want to learn component structure and how component fit within each other. We will also cover how these component communicate with each other.
Let’s try to create a sample ToDo app which can render a list of ToDos.
To begin with we will create a ToDoApp and will create child component within it and will render the todo.
Here is the structure of todo app –
We need to create 3 components here-
TodoApp
TodoList
Todo
Here is raw structure of each of them -
var TodoApp = React.createClass({
render: function () {
return (
);
}});
var TodoList = React.createClass({
render: function(){
//render all todos ()
);
});
var Todo = React.createClass({
render: function(){
return(
som items
);
}
});
This is how we will render the todo app –
ReactDOM.render(,document.getElementById('todo')); // assuming there is a div with id “todo”
Lets try to fill all these components further and see if we can have working app.
If we want to render something in our Todo app, we need to pass some data. In React we make use of props to pass any data from parent to child.
var _todos = [ {id: 1, text: "This is one comment"}, {id: 2, text: "This is *another* comment"}]; //Sample data
ReactDOM.render(,document.getElementById('todo')); // sample data passed as prop to TodoApp component.
Consume the props –
We need to consume this data in TodoApp, so let’s modify our default implementation -
var TodoApp = React.createClass({
render: function () {
return (
);
}});
If you see closely we consumed the todos pass using this.props.todos and passing it to TodoList as another prop “todos”.
let modify TodoList to consume this prop -
var TodoList = React.createClass({
render: function(){
var todos = this.props.todos; // Get list of todo from prop
var todoNodes = todos.map(function(todo){return ();}); // loop over all items and create node for each
return (
{todoNodes}
); // return the nodes
}});
If you see carefully we are looping over the todo list and then creating the node for each todo. We are passing the actual todo object as “current” prop in the todo component. Let have a look at modified code of ToDo -
var Todo = React.createClass({
render: function(){
var todo = this.props.current;
return(
{todo.id}- {todo.text}
);
}});
In the above component we are just displaying the id and text.
No comments:
Post a Comment