2

I'm practicing react and I'm trying to add an item to a list from input by clicking submit button. I prefer to use state and setState I'd LOVE some help.

I don't think my code is needed but here is it anyway:

class App extends Component {
  state = {
    userInput: ""
  }

  inputChangeHandler = (e) => {
    this.setState({userInput: e.target.value})
  }

  listAddHandler = () => {
    var listElement = document.createElement('li')
    listElement.appendChild("ul")
  }

  render() {
    return (
      <div className="checklist">
        <h1>This is an inventory</h1>
        <input type="text" value={this.state.userInput} onChange={this.inputChangeHandler} placeholder="Insert item"/>
        <button onClick={this.listAddHandler}>Submit</button>
        <ul>
          <li>
            
          </li>
        </ul>
      </div>

    )
  }
}
tanmay
  • 7,761
  • 2
  • 19
  • 38
C0deN3rd
  • 45
  • 2
  • 7

1 Answers1

3

You need to keep track of listed items within your state as an array:

const { Component } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')

class App extends Component {
  state = {
    listItems: [],
    userInput: '',
  }

  inputChangeHandler = ({target:{value}}) => this.setState({
    userInput: value
  })
  
  submitHandler = e =>{
    e.preventDefault()
    this.setState({
      listItems: [...this.state.listItems, this.state.userInput],
      userInput: ''
    })
  }    


  render() {
    return (
      <div>
        <ul>
          {
            this.state.listItems.map((li,key) => <li {...{key}}>{li}</li>)
          }
        </ul>
        <form onSubmit={this.submitHandler}>
          <input value={this.state.userInput} onChange={this.inputChangeHandler} />
          <input type="submit" value="Submit" />
        </form>
      </div>
    )
  }
}

render (
  <App />,
  rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • 1
    Thank you. Just a general question: Is using the submit HTML tag is that useful? because I always thought about using a button tag instead, why is it that useful? – C0deN3rd Jul 03 '20 at 17:03
  • Of course :) I checked it today it is good. Thank you very much – C0deN3rd Jul 04 '20 at 14:51