How to make the labels readable by screen readers in react native?

Viewed 2639

I am using accessibility scanner to check accessibility of my app.

It found that labels in my form are not readable by screen readers. I googled all day, but didn't find one example of how to do this. any help? My form code:

    import React, { Component } from 'react';
    import { TextInput } from 'react-native';
    
    const MakemeAccessible= () => {
      const [value, onChangeText] = React.useState('');
    
      return (
        <Text>Username</Text>
        <TextInput
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={text => onChangeText(text)}
          value={value}
        />
      );
    }
    
    export default UselessTextInput;

this item may not have a label readable by screen readers

1 Answers

Inputs should have associated labels, this means that screen readers can understand what an input is for, users can click on the label to focus the input etc. etc.

To do this in React you use htmlFor instead of the standard HTML for attribute.

You also need to use a <label> element instead of a <text> element for semantics and for the association to work correctly.

You assign a unique ID to each input and point htmlfor at that ID for an associated label.

return (
        <label htmlFor="uniqueInputID">Username</label>
        <TextInput id="uniqueInputID"
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={text => onChangeText(text)}
          value={value}
        />
      );

Alternatively you can simply wrap the input in a label element and this will associate the label with the TextInput correctly without the use of htrmlfor and an ID. It depends on your use case as to which you use, both are valid and nowadays both are well supported.

return (
        <label>Username
        <TextInput 
          style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
          onChangeText={text => onChangeText(text)}
          value={value}
        />
        </label>
      );

I am pretty sure the same applies for React native but it has been a while since I have used it.

Related