how do i get an attribute value on a click handler?

As explained by @DrewReese in the comments, it is impossible to get the eventKey from the DOM element (e.target) because it is never passed down to the DOM.

We should get it from the props instead. We do need to use eventKey in three places: as the eventKey prop in both the Toggle and the Collapse and in our onClick. But when it becomes abstracted out as a component prop, we only need to declare the specific event key, ie. eventKey="2", once.

import React from "react";
import { Accordion, Card } from "react-bootstrap";

interface RenderCardProps {
  eventKey: string;
  CardClick: (key: string) => void;
  /** add whatever else you need */
}

const RenderCard = ({ eventKey, CardClick }: RenderCardProps) => {
  return (
    <Card>
      <Accordion.Toggle
        as={Card.Header}
        eventKey={eventKey}
        className="faq-header"
        onClick={() => CardClick(eventKey)}
      >
        <span className="rh5">Some text</span>
      </Accordion.Toggle>
      <Accordion.Collapse eventKey={eventKey}>
        <Card.Body>
          <span className="rh6">Some text</span>
        </Card.Body>
      </Accordion.Collapse>
    </Card>
  );
};

export default () => <RenderCard CardClick={console.log} eventKey="2" />;

You probably want to make ToggleContents and CardContents into props too in order to use this as an actual component.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top