Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
pass state value as props to another component es6

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!