How to add a string to a string list in a todo list react

Viewed 464

Hi everyone am trying to add string values from this.state.todo below to the array (list) below so that i can loop through them. I need assistance

import React, {Component} from "react";
import "./styles.css";

class App extends Component {
  state = {
    todo: '',
    list: []
  }

  changeHandler = (event) => {
    this.setState({
      todo: event.target.value
    }); 
  }

  submitHandler = (event) => {
    event.preventDefault()
    this.setState({
      list: [...this.state.list, this.state.todo]
    }); 
  }

  render(){


return (
  <div className="App">
    <input type="text" onChange = {this.changeHandler} />
    <button onSubmit={this.submitHandler}> Submit </button>
    {console.log(this.state)}
  </div>
);
  }
}
export default App

2 Answers

You need to put state in constructor and bind function:

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      todo: '',
      list: []
    }
    this.changeHandler = this.changeHandler.bind(this)
    this.submitHandler = this.submitHandler.bind(this)
  }
  ...
}

you could change button event to onClick instead of onSubmit.

Or

Else If you are using onSubmit you should wrap the component with form

return (
  <div className="App">
   <form onSubmit={this.submitHandler}>
    <input type="text" onChange = {this.changeHandler} />
    <button > Submit </button>
    {console.log(this.state)}
  </form>
  </div>
)
Related