I'm able to pass data around but I'm stuck here, how to pass state of AddTodo component to Todos component? Is there anything wrong with my component structure?
class AddTodo extends React.Component {
constructor(){
super();
this.state = {text: ''};
}
onTextChanged(e){
this.setState({text:e.target.value});
}
addHandler(){
alert(this.state.text); // pass this to Todos??
}
render() {
return(
<div>
<input type="text" onChange={(e)=>this.onTextChanged(e)} />
<button onClick={()=>this.addHandler()}>Add</button>
</div>
)
}
}
class Todos extends React.Component {
constructor(){
super();
this.data = ['write book','wash clothes','jogging'];
}
render() {
return (
<div>
<AddTodo/>
<ul>
{this.data.map((item)=><TodoItems key={item} item={item}/>)}
</ul>
</div>
);
}
}
Live demo here http://jsbin.com/susadehacu/1/edit
Very simple, you just need to add a method in Todos to add an item to your list. This would then be passed into your AddTodo component as a prop.
Todos
constructor(){
super();
this.data = ['write book','wash clothes','jogging'];
}
addTodo(todo) {
// new array
let newData = this.data.slice();
newData.push(todo);
this.setState({data: newData});
}
...
<AddTodo addTodo={(todo) => this.addTodo(todo)} />
AddTodo
addHandler(){
this.props.addTodo(this.state.text);
}