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

Time:05-05

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.

CodePudding user response:

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>
  );
}

CodePudding user response:

Inder's answer using some Typescript

import styled from "styled-components/native"

interface PressableProps {
  buttonStyle?: CSSObject
}

const Pressable = styled.Pressable<PressableProps>({ buttonStyle }) => buttonStyle)

export default function App() {
  return (
    <View style={styles.container}>
      <Pressable buttonStyle={{ backgroundColor: "pink" }}>
        <Text>This is button</Text>
      </Pressable>
    </View>
  );
}
  • Related