Reputation: 103
I have a Text Input component that change its background color using onBlur and onFocus events. What I want to do is to pass another function to onBlur using props, so the component would perform both actions.
This is my component:
const Input: React.FC<TextInputProps> = (props) => {
const [color, setColor] = useState("#f2f2f2");
return (
<TextInput
onFocus={() => setColor('#f9ffc4')}
onBlur={() => setColor('#f2f2f2')} // I would like to use props.onBlur here in addition to setColor()
onChangeText={props.onChangeText}
style={{ backgroundColor: color }}
value={props.value}
>
</TextInput>
)
}
export default Input;
And this is how I use it:
return (
<Input
onChangeText={ handleChange('cpf') }
value={values.cpf}
onBlur={() => setFieldTouched('cpf')} //I want to call it along with the method declared in the component
/>
{touched.cpf && errors.cpf &&
<Text style={{ color: 'red', width: '100%', textAlign: 'right' }}>{errors.cpf} </Text>
}
)
I know that I could use setColor() here, but I have lots of other inputs and if I did that, I would have to create an useState const for each one of them, and that's not what I want.
If someone could help me here I would really appreciate it, and if something is not clear in my question, just ask me and I will try to explain better.
Upvotes: 0
Views: 1743
Reputation: 471
You need to do something like this to get rid of that error you were bothered about:
const Input: React.FC<TextInputProps> = ({onBlur, onChangeText, value}) => { destructured for code readability
const [color, setColor] = useState("#f2f2f2");
const handleBlur = (event) => {
setColor('#f2f2f2');
onBlur(event); // This is passed as a prop with its event which is needed to rid that undefined TypeError.
}
return (
<TextInput
onFocus={() => setColor('#f9ffc4')}
onBlur={handleBlur} // The function here has an event that you will need to pass.
onChangeText={onChangeText}
style={{ backgroundColor: color }}
value={value}
>
</TextInput>
)
}
export default Input;
Upvotes: 0
Reputation: 1502
onBlur={() => {
setColor('#f2f2f2');
props.onBlur();
}}
Is this what you want?
Upvotes: 1