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>
}
/>
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
I have a Mui Autocomplete Component with a react-hook-form Controller.
When I set the freeSolo attribute the value doesn't get reset. When I call for example: resetField("selBinvrk") without freeSolo everything works as expected. Here is the code for my autocomplete and the submit function. Can anybody help me with that problem?
<Controller
name={name}
control={control}
rules={rules}
render={({ field: { onChange, value } }) => (
<Autocomplete
disabled={!disabled ? false : true}
value={value}
freeSolo={freeSolo}
//autoSelect={autoSelect}
options={options}
getOptionLabel={getOptionLabel}
isOptionEqualToValue={isOptionEqualToValue}
/* getOptionSelected={(option, value) => {
console.log('get option selected: ', option, value);
return value === undefined || value === "" || option.ID === value.ID}
} */
//console.log(item);
onChange={(event, item) => {
//console.log(item);
onChange(item);
}}
//renderOption={renderOption}
renderInput={(params) => (
<TextField
{...params}
label={label}
variant="outlined"
error={isError}
helperText={errorMessage}
sx={sx}
inputRef={inputRef}
/>
)}
/>
)}
/>
const onSubmit = (data, e) => {
console.log("hä: ", e);
resetField("selBinvrk");
resetField("selMenge");
mutate({
binv_id: data.selBinv.ID,
bsa_id: data.selBinvrk?.BSA_ID || 0,
binvrk_id: data.selBinvrk?.ID || 0,
selMenge: data.selMenge,
bsm_id: data.selBsm.ID,
});
//recaptchaRef.current.execute();
//mutate(data);
};
In react native I want to make a dynamic controller component. But i cant access errors with it. I using "react-hook-form" for form elements. So Its my component :
const {
control,
handleSubmit,
formState: {errors},
setValue,
} = useForm();
const DynamicController = ({req, pattern, name, label}) => {
return (
<>
<Text style={[t.textBase]}>{label}</Text>
<Controller
control={control}
defaultValue=""
rules={{
required: {
value: true,
message: 'Bu alan boş bırakılamaz!',
},
}}
render={({field: {onChange, onBlur, value}}) => (
<Input
errorText={errors[name].message}
error={errors[name]}
onBlur={onBlur}
placeholder={label}
onChangeText={onChange}
value={value}
/>
)}
name={name}
/>
</>
);
};
My Input Component is basicly simple input. My problem is when i give error name like that example i cant access errors.
Its how i use my component :
<DynamicController
label="Email"
name="Email"
pattern={true}
req={true}
/>
When i dont fill the element and log the submit its not showing any error. Its simple passing validate. So what can i do where do i make wrong ? thank you for answerings!!!
Is your Input a custom wrapper? If not, a better way do this using react-hook-form would be:
const {
control,
handleSubmit,
formState: {errors},
setValue,
} = useForm(
defaultValues: {
firstName: '', // form fields should be populated here so that the error can be displayed appropriately
lastName: ''
}
);
const DynamicController = ({req, pattern, name, label}) => {
return (
<>
<Text style={[t.textBase]}>{label}</Text>
<Controller
control={control}
defaultValue=""
rules={{
required: {
value: true,
message: 'Bu alan boş bırakılamaz!',
},
}}
render={({field: {onChange, onBlur, value}}) => (
<Input
onBlur={onBlur}
placeholder={label}
onChangeText={onChange}
value={value}
/>
)}
name={name}
/>
{errors[name] && <Text>This is required.</Text>}
</>
);
};
I want to set the value of my custom TextInput to "" when the iconPress is called.
The problem is, that when i call the iconPress, it should clear the text of my TextInputCode field.
But it isnt updated on my screen, isnt clearing the input field.
But it just doesnt change the value/clear it...
This is my code:
const [searchString, setSearchString] = useState("");
const submitHandler = () => {
setSearchString("")}
const changeHandler = (value) => {
setSearchString(value)}
return(...
<TextInputCode
value={searchString}
onChange={(text) => {
changeHandler(text);}}
iconType={
Platform.OS === "android"
? isSearchbarFocused
? "chevron-left"
: "search"
: "search"
}
iconPress={() => {
Platform.OS === "android" && isSearchbarFocused
? (submitHandler(), setSearchbarFocused(false), Keyboard.dismiss())
: "keine suche";
}}
showCancel
placeholderTextColor={colors.text}
onFocus={() => {
setSearchbarFocused(true);
}}
/>
...)
This is the code of my TextInputCode element, but I dont think that this is the problem:
const TextInputCode = ({
iconType,
placeholder,
onChange,
onFocus,
textContentType,
autoCapitalize,
autoCompleteType,
iconPress,
onClear
}) => {
return (
<View style={styles.inputView}>
<Icon name={iconType} onPress={iconPress} size={20}
/>
<TextInput
style={{
flex: 1,
paddingHorizontal: 12,
}}
placeholder={placeholder}
textContentType={textContentType}
autoCapitalize={autoCapitalize}
autoCompleteType={autoCompleteType}
autoCorrect={false}
onChangeText={(e) => onChange(e)}
onFocus={onFocus}
onClear = {onClear}
/>
</View>
);
};
I dont understand why this isnt working. What am I doing wrong?
I have a state :
const [searchEntryNo, setSearchEntryNo] = useState('');
Then I have a function to clear state like that.
const handleClear = () => {
setSearchEntryNo('');
};
Then There React AutoComplete :
<Autocomplete
className={classes.searchBox}
id="combo-box-demo"
size="small"
options={entryList}
getOptionLabel={(option) => option}
onChange={(event, newValue) => {
setSearchEntryNo(newValue);
}}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} variant="outlined"
placeholder="Searching" size="small" />}
/>
Note: entryList is the a array state
There is a button where handleClear() function fired the button click:
<Button onClick={handleClear}> Clear </Button>
Now I want to clear selected label from AutoComplete Box after handleClear() fired.
How can I solve the issue?
Please Help me!!
onChange also passes a second parameter to the change handler: docs
onChange={(_, value: any, reason: string) => {
if (value) {
// seState
}
if (reason === "clear") {
// clear State
}
}}
I'm working with react-hook-forms and trying to reset all form fields after submit. The problem is that in my case Autocomplete accepts objects as a value.
I've tried to set the defaultValue to {}, but received the following message:
Material-UI: the getOptionLabel method of Autocomplete returned undefined instead of a string for
{}
Are there any variants how Autocomplete could be reset?
Here is a link to the CodeSandbox
A little late to the party but here's a solution if anyone else needs it.
Assuming your autocomplete is wrapped inside a Controller, all you have to do is explicitly check the value in Autocomplete. Refer below for more
<Controller
name="category"
control={control}
rules={{ required: true }}
render={({ field }) => (
<Autocomplete
fullWidth
options={categories}
{...field}
// =====================================================
// Define value in here
value={
typeof field.value === "string"
? categories.find((cat) => cat === field.value)
: field.value || null
}
// =====================================================
onChange={(event, value) => {
field.onChange(value);
}}
renderInput={(params) => (
<TextField
{...params}
label={t("product_category")}
error={Boolean(errors.productCategory)}
helperText={errors.productCategory && "Product Category is required!"}
/>
)}
/>
)}
/>
This should do the trick!
To reset the value of AutoComplete with reset of react hook form you should add the value prop to the AutoComplete, other ways the reset wont function, see the example:
import { useEffect, useState } from 'react'
import {
Autocomplete,
TextField,
reset,
} from '#mui/material'
...
const {
...
setValue,
control,
formState: { errors },
} = useForm()
useEffect(() => {
reset({
...
country: dataEdit?.country ? JSON.parse(dataEdit?.country) : null,
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dataEdit])
...
<Controller
control={control}
name="country"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange, value } }) => (
<Autocomplete
value={value || null}
options={countries}
getOptionLabel={(option) => option.name}
onChange={(event, values) => {
onChange(values)
setSelectedCountry(values)
setValue('region', null)
}}
renderInput={(params) => (
<TextField
{...params}
label="Pays"
placeholder="Pays"
helperText={errors.country?.message}
error={!!errors.country}
/>
)}
/>
)}
/>