Search code examples
react-nativereact-native-web

React Native Web - Control the html tag generated by View?


I have a react native web project. At one point, I would like my View instead of generating a <div> to generate a <label> element.

Is there a way to control this? I am hoping for some sort of htmlTag attribute that gets ignored if this is not compiling for a browser environment.


Solution

  • There was a component prop but it's removed in favor of accessibilityRole (Remove component prop).

    You can use accessibilityRole to specify the label tag and even create a custom element using it:

    function Label({ text }) {
      return <View accessibilityRole="label">{text}</View>
    }
    

    and then use it like this:

    export default class App extends React.Component {
      render() {
        return (
          <View style={styles.container}>
            <View>
              <Label text="Test input:"/>
              <TextInput name="test-input"/>
            </View>
          </View>
        );
      }
    }
    

    Check this working Expo snack: https://snack.expo.io/@clytras/change-rn-web-div-tag