Home > Software engineering >  Next Js Accrodion should be collapse when click arrow icon
Next Js Accrodion should be collapse when click arrow icon

Time:08-16

I am using Accordion in next js. I am following this (react-accessible-accordion) package.

Currently it is getting collapse when main div is getting clicked. What i want to achieve is According should be collapse when click on arrow icon not on main div.

If there is an alternate way of doing this please let me know.

UPDATE

Here is the code sandbox

What i want to achieve is explained here Thanks!

CodePudding user response:

first I had to modify the styles so the icon is not taking the full width.

Accordion.css

.accordion__icon {
  /* margin-left: auto; */
  transition: transform 0.6s ease;
}


.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  display: flex;
  align-items: center;
  border: none;
  outline: none;
  transition: background-color 0.6s ease;
  /* add flex display and justify content */
  display: flex;
  justify-content: space-between;
}


Add onClick to the main SVG and pass it through the props.

Chevron.js

// pass an onClick props to the main SVG
function Chevron(props) {
  return (
    <svg
      className={props.className}
      height={props.height}
      width={props.width}
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 320 512"
      onClick={props.onClick}
    >
      <path
        fill={props.fill}
        d="M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z"
      />
    </svg>
  );
}

export default Chevron;

Finally make the props.onClick of the Chevron component handle the onClick event not its Button parent component.

Accordion.js

...
// move the onClick from the button to the Chevron component
return (
    <div className="accordion__section">
      <button className={`accordion ${setActive}`}>
        <p className="accordion__title">{props.title}</p>
        <Chevron
          onClick={toggleAccordion}
          className={`${setRotate}`}
          width={10}
          fill={"#777"}
        />
      </button>
...)

full sandbox link

  • Related