2

I'm trying to implement a custom button using TouchableHighlight

I created a button class and I'm importing it into my main program like this:

In button.js:

export default class Button extends React.Component {
    render() {
        return (
            <TouchableHighlight>
                <View style={styles.button}>
                    <Text style={styles.buttonText}>
                    </Text>
                </View>
            </TouchableHighlight>
        )
    }
}

In app.js:

import Button from './button'


<View>
     <Button onPress={ () => navigate('Chat', { user: 'Abe' })} title = "Abe"
     />
</View> 

When I run this, I just get a blank button with no text or onPress event.

How can I pass in the onPress and title values to the Button class?

Thanks!

0

1 Answer 1

3

You need to access the props in your Button component.

export default class Button extends React.PureComponent {
  render() {
    const { onPress, title } = this.props;
    return (
      <TouchableHighlight onPress={onPress}>
        <View style={styles.button}>
            <Text style={styles.buttonText}>
              {title}
            </Text>
        </View>
      </TouchableHighlight>
    )
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

thanks, so using your example, would I keep the code in my app.js page the same? thanks again
what CSS styles should be used so that background colour will be applied to the text only also apply border-radius
Add backgroundColor property to the text style. Did you try the borderRadius property? React Native uses slightly different names for css properties (no hyphens)
i want css applied only for text but background color is applying to entire width. if write <Text><Text>click me</Text></Text> then background color is applied to text only but border radius is not applying
Sounds like your Text component is wider than you think. The backgroundColor property will only apply to the text if you style it on the text. Does the parent component have something like alignItems: 'stretch' set? Does the text have alignSelf: 'stretch' set?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.