sultanmb26
sultanmb26

Reputation: 61

Adding an input tag dynamically in React, shows for a moment then disappears

What am trying to do is to be able to add an input field dynamically. So for example, once you fill your first hobby, then you decide to add another one. you click on add and a new input field is shown. The input field is showing for split second then disappearing.

Code:

class App extends React.Component {
  state = {
    Hobbies: []
  }

  addHobby = () => {
    this.setState(prevState => ({ Hobbies: [...prevState.Hobbies, ''] }))

  }

  handleChange(i, event) {
    let Hobbies = [...this.state.Hobbies];
    Hobbies[i] = event.target.value;
    this.setState({ Hobbies });
  }

  removeClick(i) {
    let Hobbies = [...this.state.Hobbies];
    Hobbies.splice(i, 1);
    this.setState({ Hobbies });
  }

  render() {
    const widthStyle = {
      width: '15rem'
    };



    return (
      <div className="App">
        <form >
          <label>
            Hobbies:
          <input type="text" name="hobby" />
          </label>
          <br /><br />

          {
            
            this.state.Hobbies.map((el, i) => {
              return (
                <div key={i}>
                  <input type="text" value={el || ''} onChange={this.handleChange.bind(this, i)} />
                  <input type='button' value='remove' onClick={this.removeClick.bind(this, i)} />
                </div>
              )
            })
          }

          <button onClick={this.addHobby.bind(this)}>ADD Hobby</button>
        </form>

       
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));

Upvotes: 1

Views: 319

Answers (2)

ForbesLindesay
ForbesLindesay

Reputation: 10702

An alternative to using e.preventDefault() is to mark the button as being of type="button" the default inside a <form> element is type="submit" which automatically submits the form/refreshes the page.

<button type="button" onClick={this.addHobby.bind(this)}>ADD Hobby</button>

Setting `type="button" indicates that the button is just there to trigger some JavaScript action, not to submit the form.

Upvotes: 1

varoons
varoons

Reputation: 3887

The problem is you are clicking inside a form which is why your page is getting refreshed(form submits) and you lose the state

addHobby = (e) => {
  e.preventDefault() //<-----
  this.setState({ Hobbies: [...this.state.Hobbies, ''] })
}

CodeSandbox

Upvotes: 3

Related Questions