Search code examples
javascriptreactjsreact-nativestyled-components

Add styles to Styled Component custom Component in React Native


I have button.js:

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

const StyledButton = styled.TouchableOpacity`
  border: 1px solid #fff;
  border-radius: 10px;
  padding-horizontal: 10px;
  padding-vertical: 5px;
`;

const StyledButtonText = styled.Text`
  color: #fff;
  font-size: 12;
`;

export default ({ children }) => (
  <StyledButton>
    <StyledButtonText>{children.toUpperCase()}</StyledButtonText>
  </StyledButton>
);

And its usage:

import React, { Component } from "react";
import styled from "styled-components";
import Button from "./button";

const StyledNavView = styled.View`
  justify-content: flex-end;
  flex-direction: row;
  background: #000;
  padding-horizontal: 10px;
  padding-vertical: 10px;
`;

const StyledTodayButton = styled(Button)`
  margin: 10px;
`;

export default class Nav extends Component {
  render() {
    return (
      <StyledNavView>
        <StyledTodayButton>Today</StyledTodayButton>
        <Button>Previous</Button>
      </StyledNavView>
    );
  }
}

Problem is, the margin I apply in StyledTodayButton is actually never applied. Have I misunderstood extending styles in Styled Components?


Solution

  • There are 2 ways to make it work:

    • extend button style:

    const StyledTodayButton = Button.extend'margin: 10px'

    • pass prop to button:
    const Button = styled.button'
    
    /* ...your props */
    
    margin: ${props => props.withMargin ? '10px' : '0px'};
    

    and then call in render method you can invoke it with:

    <Button withMargin  {...restProps} />