Search code examples
reactjsreact-nativecomponentstypechecking

react-native type check on component


I have a component that I want to be able to handle two kinds of components. One is a Text component, the other Image component.

I have some default styles like the color I want to be able to apply that to both components, however, a text element can use the key of color in its styles, but on an Image, it has to be tintColor key.

Is there any way I can check for which element I have so I can set the appropriate styles to each one?


Solution

  • If I understood correctly, you can use 3 styles object to handle it like this:

    const styles = StyleSheet.create({
      default: { marginTop: 10, borderWidth: 1 },
      onlyButton: { borderColor: '#F0F' },
      onlyText: { borderColor: '#C9F' },
    })
    
    <Text style={[styles.default, styles.onlyText]} />
    <TouchableOpacity={[styles.default, styles.onlyButton]} />
    

    Note that the code above might have typos, it's just an example to show the idea.

    Let me know if it helped, or if I misunderstood your question.

    Hope it helps