Search code examples
reactjsonclickaccordion

ReferenceError: handleClick is not defined | Next.js


I'm getting a ReferenceError: handleClick is not defined error in my React code, and I'm not sure how to resolve it. Here is the code that's causing the error:

const services = [
  {
    title: (
      <AccordionHeader>
        <AccordionLeft>
          <span>01</span>
        </AccordionLeft>
        <AccordionRight className="icon-container">
          <p>Project Name</p>
          <BsArrowRight
            onClick={handleClick}
            className={`icon ${rotate ? "rotate" : ""}`}
          />
        </AccordionRight>
      </AccordionHeader>
    ),
    content: <>{/* CODE */}</>
  }
];

const ProjectsPage = () => {
  const [rotate, setRotate] = useState(false);

  const handleClick = () => {
    setRotate(!rotate);
  };
  return (
    <>
      {services.map((services, index) => (
        <>
          <Accordion
            key={index}
            title={services.title}
            content={services.content}
          />
          <HrLine />
        </>
      ))}
    </>
  );
};

export default ProjectsPage;

I have defined the handleClick function within the component, but I'm still getting this error. How can I fix this issue?

My error is: enter image description here


Solution

  • When you define services, handleClick is indeed not defined. It only exists within the scope of the ProjectsPage component.

    Move the definition of services to within the component.:

    const ProjectsPage = () => {
      const [rotate, setRotate] = useState(false);
    
      const handleClick = () => {
        setRotate(!rotate);
      };
    
      const services = ... // <-- here
    

    Alternatively, if you want to keep it outside the component, make it a function and pass it the value it needs. For example:

    const services = (handleClick) => [
      //...
    ];
    

    And then in the component:

    {services(handleClick).map((services, index) => (