0

building an accordion style component so that in the collapsed state, only the first 40 characters are displayed, and when expanded the user can see the entire content. I’m new to React/Styled Components but feel like I’m repeating my styles a lot when there is bound to be a more efficient way to chain on styles to existing components, can anyone advice?

const Accordion = styled.div`
  background-color: #e5e9eb;
  height: 87px;
  width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;
  display: flex;
  align-items: center;

  span {
    font-size: 14px;
    line-height: 20px;
    padding-left: 24px;
  }
`;

const AccordionExpanded = styled.div`
  background-color: #e5e9eb;
  height: 174px;
  width: 612px;
  border-radius: 2px;
  border: 1px solid #27282a;
  margin-bottom: 48px;
  display: flex;
  align-items: center;

  span {
    font-size: 14px;
    line-height: 20px;
    padding-left: 24px;
  }
`;

const Title = styled.h3`
font-size: 12px;
letter-spacing: 1px;
text-transform: uppercase;
padding-left: 24px;
`;

const ExpandIcon = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
`;

const CollapseIcon = styled.img`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
-webkit-transform: rotate(180deg);
`;

const ExpandableString = ({ attribute, className }: Props) => {
  const [isExpanded, setIsExpanded] = React.useState(false);
  const fullDescription = attribute.readonlyvalue;
  const shortHeading = fullDescription.substring(0, 40) + '...';

  function toggleContent() {
    setIsExpanded(prev => !prev);
  }

  return (
    isExpanded ? <AccordionExpanded className={className}>
      <Title>Goods being sent</Title>
      <span>{fullDescription}</span>
      <CollapseIcon onClick={toggleContent} src={chevron} alt="Collapse content" />
    </AccordionExpanded> : <Accordion className={className}>
      <Title>Goods being sent</Title>
      <span>{shortHeading}</span>
      <ExpandIcon onClick={toggleContent} src={chevron} alt="Expand content" />
    </Accordion>
  );
};
Anonymous Asked question May 14, 2021