TeamWertarbyte / material-ui-chip-input

A chip input field using Material-UI.
https://mui.wertarbyte.com/#material-ui-chip-input
MIT License
737 stars 208 forks source link

Form is being submitted when returning false from "onBeforeAdd" #326

Closed ahmed3hamdan closed 4 years ago

ahmed3hamdan commented 4 years ago

In the following example, the form is being submitted when adding a value less than 3 characters long

import React from "react";
import ChipInput from "material-ui-chip-input";

const MyForm = () => {
  const handleSubmit = e => {
    e.preventDefault();
    console.log("submitted");
  };
  return (
    <form onSubmit={handleSubmit}>
      <ChipInput onBeforeAdd={value => value.length >= 3} />
    </form>
  );
};

export default MyForm;

My solution to overcome the issue:

import React from "react";
import ChipInput from "material-ui-chip-input";

const MyForm = () => {
  const handleSubmit = e => {
    e.preventDefault();
    console.log("submitted");
  };
  const handleKeyDown = e => {
    if (e.keyCode === 13 && e.target.value.length < 3) {
      e.preventDefault();
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <ChipInput onKeyDown={handleKeyDown} />
    </form>
  );
};

export default MyForm;
ahmed3hamdan commented 4 years ago

This behavior can be fixed by using "onKeyPress" to prevent the form from being submittied

import React from "react";
import ChipInput from "material-ui-chip-input";

const MyForm = () => {
  const handleSubmit = e => {
    e.preventDefault();
    console.log("submitted");
  };
  const handleKeyPress = e => {
    if (e.key === "Enter") e.preventDefault();
  };
  return (
    <form onSubmit={handleSubmit}>
      <ChipInput onKeyPress={handleKeyPress} onBeforeAdd={value => value.length >= 3} />
    </form>
  );
};

export default MyForm;