2
votes

I have been working with Styled Components for a while now but I'll be honest I never really understood how it works. That is what my question is about.

So, I understand styled components can adapt based on props. What I don't understand is how does the forwarding of props work.

For Example in my case, Im working with React Native. There are some default props which I have given to my input field. Now, styled component wrapper automatically picks up the default height prop but If I explicitly pass the prop it does not pick it up and I have to manually get it from props. What is that about?

import React from "react";
import styled from "styled-components/native";

const StyledTextInput = styled.TextInput`
   /* Why do I have to do this for custom heights.
    * Isn't height automatically get forwarded?
    */

  /* if I comment this height style out, It takes defaultProp height but doesn't take custom height
   * I have to uncomment it for the custom height
   */

  height: ${({ height }) => height};

   ...other styles
`;

const TextInput = ({ height }) => {
  return <StyledTextInput height={height} />;
};

TextInput.defaultProps = {
  height: 50
};

export default TextInput;


// Then In some Smart Component
class App extends Component {
  render() {
    return (
      <View style={styles.app}>
        <TextInput height={200} /> // ???
        ...other stuff
      </View>
    );
  }
}

Here are my Questions:

  • What are the cases in which styled component automatically picks up the prop?
  • Which props are automatically forwarded.
  • How does this prop forwarding work?

Documentation doesn't talk much about that or maybe I have missed it.

Any help would be much appreciated.

1

1 Answers

1
votes

All standard attributes are automatically forwarded props. Standard attributes like defaultValue and type. Take note of the camel case notation for attributes in React.

If it's a custom attribute like someCustomAttribute prop, it's not passed directly to DOM.

If there are props that are true to all instances of the styled component, you can make use of .attrs.

const StyledTextInput = styled.TextInput.attrs(props => ({
  height: props.height
}))`
  // other styles
`