Home > Enterprise >  A way to Highlight <Pressable/> component in react-native?
A way to Highlight <Pressable/> component in react-native?

Time:10-06

So im using the Pressable Component in react-native instead of using Button because i've heard it has many limitations regarding styling. I've tried using TouchableHighlight as well but it isnt working porperly for me moreso since my Component already has some styling and Positioning adjusted into it

class randomComponent extends Component {



    render() {
    
    return (
      <Pressable>
        <Text>Hello World</Text>
      </Pressable>
      )
    
    }
tl:dr How do i Highlight a Pressable Component? thanks

CodePudding user response:

Solution:

 import { TouchableOpacity } from 'react-native'

TouchableOpacity is better for developers with experience in a web-based background and styling.

CodePudding user response:

You need to use a state variable to store the pressed state and change the component style accordingly

class randomComponent extends Component {
    constructor(props) {
      super(props)
      
      this.state = {
         pressed: false
      }
    }


    render() {
    
      return (
        <Pressable 
          onPressIn={() => this.setState({pressed: true})} 
          onPressOut={() => this.setState({pressed: false})}
          style={this.state.pressed ? styles.pressed : {}}
        >
          <Text>Hello World</Text>
        </Pressable>
      )
    
}

const styles = StyleSheet.create({
  pressed: {
    backgroundColor: 'red'
  }
})
  • Related