I admit, I am not a React Native dev, but I have been looking into a project where the devs has a problem getting onFocus triggered when attaching a keyboard to a phone (yes, it sounds strange, but it is for accessibility reasons).
I have experimented with different approaches to getting a trigger when the pressable receives focus, but to no avail. Here are the things I tried.
Using 'focused' variable
I have tried using the 'focused' variable, but that does not work (doesnt seem to be triggered, but builds and can run). The 'pressed' variable works fine though:
return (
<Pressable
accessible={true}
accessibilityRole="button"
accessibilityLabel={title}
style={({ pressed, focused }) => [
styles.container,
{
backgroundColor: pressed
? theme.colors.buttonPressed
: (focused
? theme.colors.buttonFocused
: theme.colors.buttonNormal),
},
disabled ? styles.disable : styles.able,
]}
disabled={disabled}
onPress={onPress}
>
<View style={[styles.container, style]}>
{leftIcon && leftIcon}
<Text numberOfLines={1} style={[styles.buttonText, textStyle]}>
{title}
</Text>
{rightIcon && rightIcon}
</View>
</Pressable>
);
Using onFocus events
Here I try to handle it manually:
constructor(props) {
super(props);
this.state = { isFocused: false };
}
// ....
handleFocus = () => this.setState({ isFocused: true });
handleBlur = () => this.setState({ isFocused: false });
// ...
return (
<Pressable
accessible={true}
accessibilityRole="button"
accessibilityLabel={title}
style={({ pressed }) => [
styles.container,
{
backgroundColor: pressed
? theme.colors.buttonPressed
: (this.state.isFocused
? theme.colors.buttonFocused
: theme.colors.buttonNormal), // Updated to buttonNormal
},
disabled ? styles.disable : styles.able,
]}
disabled={disabled}
onPress={onPress}
onFocus={this.handleFocus} // Handle focus using class method
onBlur={this.handleBlur} // Handle blur using class method
>
<View style={[styles.container, style]}>
{leftIcon && leftIcon}
<Text numberOfLines={1} style={[styles.buttonText, textStyle]}>
{title}
</Text>
{rightIcon && rightIcon}
</View>
</Pressable>
);
I also tried to remove the style= from the View, thinking maybe it overrode the Pressable style, but it did not change anything.