Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add props into styled-component via custom component

I'm trying to pass some props when I use my custom component with Styled-component.

This is the container I want to focus on, and I want to change the flex-direction via props:

const InputInnerContainer = styled.View`
  width: 100%;
  height: 42px;
  padding-horizontal: 5px;
  flex-direction: ${props => props.right ? "row-reverse": "row"};
  align-items: center;
  justify-content: space-between;
  border-radius: 4px;
  border-width: 1px;
  background-color: ${inputBackgroundColor};
  border: 2px solid ${inputBorderColor};
`;

This is my custom component "Input":

const Input = ({ onChangeText, icon, value, label,iconPosition}) => {
  return (
    <InputContainer>
      {label && <LabelText>{label}</LabelText>}
      <InputInnerContainer {...iconPosition}>
        <View>{icon && <LabelText>{icon}</LabelText>}</View>
        <InputField onChangeText={onChangeText} value={value} />
      </InputInnerContainer>
    </InputContainer>
  );
};

And this is where I call the custom component:

<Input
        label="Password"
        onChangeText={(text) => onChangeText(text)}
        value={value}
        icon="HIDE"
        iconPosition="right"
      />

The props I want to pass is "iconPosition". But I'm not sure how to pass it into the Styled-component. I'm still relatively new to Styled-component, so any ideas are welcome.

like image 735
William Pham Avatar asked Aug 31 '25 10:08

William Pham


1 Answers

Try without destructuring it. Not this way:

<InputInnerContainer {...iconPosition}/>

But this way:

<InputInnerContainer iconPosition={iconPosition}/>

You also need to update your styled component:

const InputInnerContainer = styled.View`
  ...
  flex-direction: ${props => props.iconPosition === "right" ? "row-reverse" : "row"}
  ...
`
like image 112
G.Artun Avatar answered Sep 02 '25 22:09

G.Artun