Search code examples
javascriptreactjsreact-nativestyled-components

React Native Styled Components how to pass non specific styles as props for re usable components


Given the following simple component example which uses styled components for the Pressable:

const StyledPressable = styled.Pressable = props => props.buttonStyle

const Icon: FC<{buttonStyle: string}> = ({buttonStyle}) => {

return ( 
<StyledPressable buttonStyle={buttonStyle} >
  <SomeIconComponent/>
</StyledPressable>
       )
 }

I would like to create a reusable component which takes in style props while still using styled components. Normally using the vanilla react native styles, this is really simple one would just pass in the style object as a prop an use it as a value in the necessary component. How would i achieve this behavior using styled components? my initial guess is that the buttonStyle has to be a string in the same format as styled components, but how would i make it so that the style which is declared inside the '' of lets say StyledPressable in this example is equal to the passed buttonStyle prop?

Since i am learning styled components, i am very open to any other way to achieve this behavior while using styled components.


Solution

  • import styled from "styled-components/native"
    const Pressable = styled.Pressable(props => (props.buttonStyle))
    
    export default function App() {
      return (
        <View style={styles.container}>
          <Pressable buttonStyle={{ backgroundColor: "pink" }}>
            <Text>This is button</Text>
          </Pressable>
        </View>
      );
    }