Search code examples
javascriptreactjsinputonchange

React - Adding an item to a list from an input by clicking submit button


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>

    )
  }
}

Solution

  • 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>