seawind543 / react-token-input

A react token (tag) input component. Allow customize data structure and Look & Feel
https://seawind543.github.io/react-token-input/
MIT License
28 stars 7 forks source link

Set onGetTokenErrorMessage to truly optional #82

Closed seawind543 closed 2 years ago

seawind543 commented 2 years ago

[Impact versions] Since v2.0.0

[Issue] Will get the console error as below when all the following 3 conditions are true.

"onGetTokenErrorMessage" is required when "ErrorType" not "string"

  1. ErrorType is neither string nor Nullish
  2. Do not provide prop onGetTokenErrorMessage
  3. Apply the built-in Token component

However, the user of TokenInput could make their own error look & feel into the built-in Token component via onGetTokenDisplayLabel without applying onGetTokenErrorMessage. In this case, the onGetTokenErrorMessage will be meaning less to provide. The user will need to make a dummy onGetTokenErrorMessage (return undefined [1]) to bypass the console error.

[1] The built-in Token component will apply the string type return value of onGetTokenErrorMessage as the title attribute

[Example code]

const handleTokenValueValidate = (tokenValue) => {
  const num = parseInt(tokenValue, 10);

  if (Number.isNaN(num) === true) {
    return new Error('Input value is not a number');
  }

  return null;
};

const handleGetTokenDisplayLabel = (tokenValue, tokenMeta) => {
  const { error } = tokenMeta;
  if (error instanceof Error) {
    return `${tokenValue} with error: ${error.message}`;
  }

  return `${tokenValue}`;
};

const ExampleDefault = () => {
  const [values, setValues] = useState([]);

  return (
    <TokenInput
      tokenValues={values}
      onTokenValuesChange={setValues}
      onGetTokenDisplayLabel={handleGetTokenDisplayLabel}
      onTokenValueValidate={handleTokenValueValidate}
      // provide to avoid rise Error
      // onGetTokenErrorMessage={() => undefined}
    />
  );
};