简体   繁体   中英

Making a Styled component (img) behave like a button

I've created a component that looks exactly how I want it to look - but the icons ( CollapseIcon & ExpandIcon ) need to be tabbale so I user can open the accordion via their keyboard. I've tried wrapping them in a button element but it destroys the styling of the page. I've added role="button" and tabindex but to no avail - can anyone suggest a good solution?

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

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

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

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

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

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 Button = styled.button`
`;

const IconButton = styled.button`
height: 40px;
width: 40px;
float: right;
margin-right: 12px;
background-color: red;
`;

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
        <CollapseIcon role="button" tabindex="0" onKeyDown={toggleContent} onClick={toggleContent} src={chevron}/>
      </Title>
      <span>{fullDescription}</span>
    </AccordionExpanded> : 
    <Accordion className={className}>
      <Title>Goods being sent
        <ExpandIcon role="button" tabindex="0" onKeyDown={toggleContent} onClick={toggleContent} src={chevron} />
      </Title>
      <span>{shortHeading}</span>
    </Accordion>
  );
};

You are so close to the answer.

The first character of Index should be captialized

tabIndex={0}

Here is the workable codesandbox for your reference.

https://codesandbox.io/s/styled-components-forked-v3wy9?file=/index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM