-1

i have a prop in a component which is onPress, when onPress is true, i want to render TouchableOpacity or View if onPress is false, this is my code:

const Card: FC<CardProps> = ({ title, subTitle, onPress }) => {
  return (
    <Container onPress={onPress}>
      ...

const Container = styled.View`
  flex-direction: row;
  padding-horizontal: 7px;
  padding-vertical: 12px;
  background-color: #fff;
  shadow-opacity: 0.08;
  shadow-radius: 25px;
  elevation: 8;
  shadow-color: rgb(0, 0, 0);
  shadow-offset: 0px 1px;
  border-radius: 8px;
  margin-bottom: 10px; 
`;

what i want to avoid is making another constant declaration, e.g.:

const TouchableContainer = styled.TouchableOpacity`
  flex-direction: row;
  padding-horizontal: 7px;
  padding-vertical: 12px;
  background-color: #fff;
  shadow-opacity: 0.08;
  shadow-radius: 25px;
  elevation: 8;
  shadow-color: rgb(0, 0, 0);
  shadow-offset: 0px 1px;
  border-radius: 8px;
  margin-bottom: 10px; 
`;

and do:

onPress? <ToucableContainer> : <Container>

cause it would feel redundant? i am confused with higher order component so i want to know what's the right approach to this? THanks

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

1 Answers1

0

this feels weird to declare a styled component inside a component for me but this is what i did:

const Card: FC<CardProps> = ({ title, subTitle, onPress }) => {
  const StyledContainer = styled(onPress ? TouchableOpacity : View)`
    flex-direction: row;
    padding-horizontal: 7px;
    padding-vertical: 12px;
    background-color: #fff;
    shadow-opacity: 0.08;
    shadow-radius: 25px;
    elevation: 8;
    shadow-color: rgb(0, 0, 0);
    shadow-offset: 0px 1px;
    border-radius: 8px;
    margin-bottom: 10px; 
  `;
return (
 <StyledContainer {...(onPress && { onPress })}>

works for me anyway, let me know if there's a better approach

gpbaculio
  • 5,693
  • 13
  • 60
  • 102