react-toolkit icon indicating copy to clipboard operation
react-toolkit copied to clipboard

[Bug] Date : Value is not updated properly

Open Kubik-a opened this issue 2 years ago • 1 comments

Issue and Steps to Reproduce

There is an issue with Date component, value is not updated properly :

const Date = forwardRef<HTMLInputElement, Props>(
  ({ className, classModifier, value, ...otherProps }, ref) => {
    const componentClassName = getComponentClassName(
      className,
      classModifier,
      'af-form__input-date'
    );

    let currentValue;
    if (value) {
      const monthFormatted = `0${value.getMonth() + 1}`.slice(-2);
      const dayFormatted = `0${value.getDate()}`.slice(-2);
      currentValue = `${value.getFullYear()}-${monthFormatted}-${dayFormatted}`;
    }

    //value prop is not passed to component ( it's not in otherProps because it's destructured before )
    return (
      <input
        className={componentClassName}
        type="date"
        defaultValue={currentValue}
        ref={ref}
        required={classModifier?.includes('required')}
        {...otherProps}
      />
    );
  }
);

Versions

2.2

Kubik-a avatar Jan 10 '24 11:01 Kubik-a

After many tests, here is how to fix it from tag 2.3.1.

  1. The defaultValue attribute is used instead of the couple value and onChange, which renders a readonly field. So the "defaultValue" attribute of the input must be replaced by "value".
  2. The calculation of currentValue is incorrect, which breaks data input after replacing the defaultValue attribute with value. The getFullYear() function does not work when the user is typing the date, as he has not finished typing. To fix this and always retrieve a valid year, we need to add zero padding to always have a 4-digit year.
  3. The onChange function defined in the handlers constant is not executing the onChange function correctly. It should execute even if the newValue is falsy, because otherwise emptying the field or resetting it with the date-picker does nothing.

With these three changes the component works as expected, responding well to user interaction and state changes.

Note : a new stable version of the toolkit will be available soon (3.0.0), this solution needs to be tested against it before proposing a pull request.

VibrantMoose avatar Oct 08 '24 09:10 VibrantMoose