Reputation: 2968
What is reactTag
parameter in AccessibilityInfo.setAccessibilityFocus(reactTag)
method? React native documentation don't provide any information about this parameter:
Set accessibility focus to a React component. On Android, this is equivalent to UIManager.sendAccessibilityEvent(reactTag, UIManager.AccessibilityEventTypes.typeViewFocused);.
I don't have any background of Objective-C
and Java
. A little example will be more appreciated. Thank !!!
Upvotes: 7
Views: 4663
Reputation: 5240
An example for functional components. When the component loads, the screen-reader focus will be set to the top element.
const myComponent = () => {
const topRef = useRef<View>(null);
useEffect(() => {
if (topRef.current) {
const reactTag = findNodeHandle(topRef.current);
reactTag && AccessibilityInfo.setAccessibilityFocus(reactTag);
}
});
return (
<>
<View ref={topRef}>Top</View>
<View>Middle</View>
<View>Bottom</View>
</>
)
}
Note that a big gotcha of this solution is that the component you wish to focus needs to be able to take a ref. If you're using a library, such as React Native Paper, these components may not take refs out of the box. If they don't, you'll need to use vanilla React Native components. Or make a PR against the library adding ref pass-through.
Upvotes: 0
Reputation: 19748
reactTag
is simply a number that is used by react to identify view objects in your application. It is the result of findNodeHandle
function, which takes a view reference as parameter.
Here's a simple example on how you can use it:
import React, {Component} from 'react'
import {
...
findNodeHandle,
...
} from 'react-native';
class Sample extends React.Component {
constructor(props) {
super(props)
this.viewRef = null;
}
...
componentDidMount() {
if (this.viewRef) {
const reactTag = findNodeHandle(this.viewRef);
AccessibilityInfo.setAccessibilityFocus(reactTag);
}
}
render() {
return (
<View ref={el => { this.viewRef = el }}>
...
</View>
)
}
}
Upvotes: 11