Search code examples
javascriptreact-nativestyled-componentstemplate-literals

how to use same style on different component with styled-components


i have this two component in React-native

const TouchableContainer = styled.TouchableOpacity`
  flex: 1;
  background-color: ${(props: any) => (props.expired ? '#ebebeb' : '#ffffff')};
  flex-direction: row;
  display: flex;
  padding-horizontal: 20px;
  padding-vertical: 12px;
  border-radius: 20px;
  margin: 3px 15px 3px 15px;
  shadow-color: #000;
  shadow-opacity: 0.23;
  shadow-radius: 2.62px;
  shadow-offset: 0px 3px;
  elevation: 4;
`;

const CardView = styled.View`
  flex: 1;
  background-color: ${(props: any) => (props.expired ? '#ebebeb' : '#ffffff')};
  flex-direction: row;
  display: flex;
  padding-horizontal: 20px;
  padding-vertical: 12px;
  border-radius: 20px;
  margin: 3px 15px 3px 15px;
  shadow-color: #000;
  shadow-opacity: 0.23;
  shadow-radius: 2.62px;
  shadow-offset: 0px 3px;
  elevation: 4;
`;

the style is the same so this is way to factorise it : (i didn't found a solution easly so it's a working answer )


Solution

  • 
    
    const style = `
      flex: 1;  
      flex-direction: row;
      display: flex;
      padding-horizontal: 20px;
      padding-vertical: 12px;
      border-radius: 20px;
      margin: 3px 15px 3px 15px;
      shadow-color: #000;
      shadow-opacity: 0.23;
      shadow-radius: 2.62px;
      shadow-offset: 0px 3px;
      elevation: 4;
    `;
    
    const TouchableContainer = styled.TouchableOpacity`
      ${style}
      background-color: ${(props: any) => (props.expired ? '#ebebeb' : '#ffffff')};
    `;
    
    const CardView = styled.View`
      ${style}
      background-color: ${(props: any) => (props.expired ? '#ebebeb' : '#ffffff')};
    `;