N Sharma
N Sharma

Reputation: 34497

How to customize TouchableOpacity and reuse in each component

I am trying to customize TouchableOpacity with below style

<TouchableOpacity
  onPress={() => {
    navigate("EnableNotification");
  }}
>
  <View
    style={{
      backgroundColor: "#FE434C",
      alignItems: "center",
      justifyContent: "center",
      borderRadius: 10,
      width: 240,
      marginTop: 30,
      height: 40
    }}
  >
    <Text style={{ color: "white" }}>CONTINUE</Text>
  </View>
</TouchableOpacity>

I have this TouchableOpacity in each component. I want something like customize this view in one js file & reuse this. Wherever I want to use this simply implement onPress and Text. How can I achieve this ?

Upvotes: 1

Views: 3194

Answers (1)

MattyK14
MattyK14

Reputation: 2126

Here's a snippet of one of the buttons I have created. The textStyle & buttonStyle are both in this component excluded, but if you wanted them to be variable you would pass it through RoundButton = ({ textStyle, buttonStyle })

const RoundButton = ({ onPress, children }) => {

  return (
    <TouchableOpacity onPress={onPress} style={buttonStyle}>
      <Text style={textStyle}>{children}</Text>
    </TouchableOpacity>
  );
};

And here's a use case:

<RoundButton onPress={this.onSubmit.bind(this)>Confirm</RoundButton>

So, you could go:

const Button = ({ onPress, buttonText }) => {
  const { buttonStyle, textStyle } = styles;

  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={{ color: '#fff' }}>{buttonText}</Text>
    </TouchableOpacity>
  );
};

const styles = {
  backgroundColor: '#FE434C',
  alignItems: 'center',
  justifyContent: 'center',
  borderRadius: 10,
  width: 240,
  marginTop: 30,
  height: 40,
}

then import { Button } from '../somepath/Button.js;

Where it will be a useable custom JSX element.

return (
...

<Button onPress={() => navigate('EnableNotification'}>CONTINUE</Button>

...
)

EDIT: Update for passing styling:

const Button = ({ onPress, buttonText, buttonStyle, textStyle }) => {

      return (
        <TouchableOpacity onPress={onPress} style={buttonStyle}>
          <Text style={textStyle}>{buttonText}</Text>
        </TouchableOpacity>
      );
    };

Your use case would be:

import { Button } from '../somepath/Button.js';

class MyPage extends Component {
  render() {
    return (
      ...
      <Button buttonStyle={styles.yourStyle} textStyle={styles.yourStyle2} onPress={() => navigate('EnableNotification')>CONTINUE</Button>
      ...
    )
  }
}

const styles = {
  yourStyle: {
    ...
  }

  yourStyle2: {
    ...
  }
}   

Upvotes: 1

Related Questions