The IT gal
The IT gal

Reputation: 215

When the input is blank the last chip should be deleted on pressing Backspace

Screen shot for referenceWhen the Input is blank and user presses delete button the last chip should be deleted. You can find the sandbox link below which can provide a clear picture.

https://codesandbox.io/s/thirsty-glade-my5xk

Any help will be appreciated.

I have tried onKeyUp function but it isn't the solution I need.

// displaying chips

{this.state.emails.map(email => (
  <div key={email}>
    {email}

    <button
      type="button"
      onClick={() =>  this.handleDelete(email)}
    >
      &times;
    </button>
  </div>
))}    

// Input field

<input
  placeholder="Type or paste email addresses and press `Enter`"
  value={this.state.value}
  onChange={this.handleChange}
  onKeyDown={this.handleKeyDown}
/>

// Delete event handeler

handleDelete = (toBeRemoved) => {
  this.setState({
    emails: this.state.emails.filter(email => email !== toBeRemoved)
  });
};

Upvotes: 1

Views: 806

Answers (2)

Steve Holgado
Steve Holgado

Reputation: 12071

You can remove your handlekeyUp and handle the backspace key in your handleKeyDown handler like this:

handleKeyDown = evt => {

  if (["Enter", ",", "Backspace"].includes(evt.key)) {
    evt.preventDefault();

    if (evt.key === "Backspace") {
      // Remove last email
      this.setState({
        emails: this.state.emails.slice(0, -1);
      })

      return;
    }

    var email = this.state.value.trim();

    if (email) {
      this.setState({
        emails: [...this.state.emails, email],
        value: ""
      });
    }
  }
};

Upvotes: 1

HARSH MODI
HARSH MODI

Reputation: 91

if (evt.key === "Backspace" && this.state.value === "") {
  evt.preventDefault();
  let emails = this.state.emails
  if (emails.length > 0) {
    emails.pop()
    return this.setState({emails})
  }
}

This should check if value is empty and evt.key is Backspace then remove last item from the emails array.

Upvotes: 1

Related Questions