Catch Pressable press with styled-components in React Native
Asked Answered
R

2

6

Is there a way to pass the pressed property to styled-components?

What I have now:

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledPressable = styled(Pressable)``;

const App = () => {
  return (
    <View>
      <StyledPressable
        onPress={() => null}
        android_ripple={{ color: 'black', borderless: true }}>
        <Text>Log in</Text>
      </StyledPressable>
    </View>
  );
};

export default App;

What I want to achieve

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledPressable = styled(Pressable)`
  background-color: ${props => pressed ? 'black' : 'blue'}    // change color on press, eg.
`;

const App = () => {
  return (
    <View>
      <StyledPressable
        onPress={() => null}
        android_ripple={{ color: 'black', borderless: true }}>
        pressed={pressed}    // this property "pressed" does not exist.
        <Text>Log in</Text>
      </StyledPressable>
    </View>
  );
};

export default App;

This is the official docs. It uses inline style and I can't make this work with styled components.

Revivalism answered 15/10, 2020 at 0:54 Comment(0)
Z
11

I don't think there is a way currently. A work around would be to use a View between Pressable and Text and do all you styling in it:

import React from 'react';
import { Pressable, Text, View } from 'react-native';
import styled from 'styled-components/native';

const StyledView = styled.View`
   background-color: ${({pressed}) => pressed ? 'black' : 'blue'}    
`;

const App = () => {
    return (
        <View>
           <Pressable onPress={() => null}>
             {({pressed}) => (
               <StyledView pressed={pressed}>
                 <Text>Log in</Text>
               </StyledView>
             )}
           </Pressable>
        </View>
    );
};

export default App;
Zonda answered 18/10, 2020 at 19:25 Comment(0)
L
0

Yes, there is a way to use 'pressed', use a function that returns an array.

<View style={styles.buttonView}>
    <Pressable
        onPress={() => doSomething()}
        style={({ pressed }) => {
            return [
                pressed
                    ? globalStyles.buttonSelected
                    : globalStyles.buttonUnselected,
            ];                                                                  
        }}> 
        <Text style={globalStyles.buttonUnselectedText}>
            Terminate session
        </Text>
    </Pressable>
</View>   
Lathrope answered 21/4, 2023 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.