Home > Software engineering >  React Native, set state onChange check value
React Native, set state onChange check value

Time:01-16

I have a search input, I would like to fire the event, trackButtonClickEventAction(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT) when the user interacts with the field. However, the event is fired when the user enters a digit, I would like to fire the event when a number has been entered and the input loses focus, any ideas?

  const onChange = (args) => {
    const inputValue = args[0].nativeEvent.text;
    if (state.reg.length === 0) {
      console.log(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT);
      trackButtonClickEventAction(
        buttonClick.MY_VEHICLES_ADD_VEHICLE_REG_INPUT,
      );
    }

    if (inputValue) {
      console.log(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG);
      trackButtonClickEventAction(buttonClick.MY_VEHICLES_ADD_VEHICLE_REG);
      setState((prevState) => ({
        ...prevState,
        reg: inputValue,
        disableButton: false,
      }));
    } else {
      setState((prevState) => ({
        ...prevState,
        reg: '',
        disableButton: true,
      }));
    }
    return inputValue;
  };

Controller:

  <Controller
    as={<InputField />}
    control={control}
    label="Number plate"
    name="reg"
    value={state.reg}
    defaultValue={state.reg}
    onChange={onChange}
    rules={{ required: true }}
    errorMessage={getError(errors.reg)}
    resetOnEmpty
    rightIcon={
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => {
          handleSubmit(onSubmit)();
          console.log(buttonClick.MY_VEHICLE_ADD_VEHICLE_INPUT_BUTTON);
          trackButtonClickEventAction(
            buttonClick.MY_VEHICLE_ADD_VEHICLE_INPUT_BUTTON,
          );
        }}
        style={forms.rightIcon}>
        <Icon
          name="search"
          size={32}
          color="#707070"
          style={forms.searchStyle}
        />
      </TouchableOpacity>
    }
  />

CodePudding user response:

You can make use of the onBlur property. onBlur will get called when the input loses focus.

<input
  onBlur={(e) => {
    console.log('input lost focus', e);
  }}
  onFocus={(e) => {
    console.log('input gained focus', e);
  }}
/>
  • Related