0

I have a problem on my next js app. I am trying to add a class on an element by clicking on a button. The problem is that when i try to access the next div, through the code below

console.log(e.target.closest('.request_quote').querySelector('hiddenSection'));

I get this error:

Property 'closest' does not exist on type 'EventTarget'

import React from 'react';
import styles from './styles.module.scss';

/**
 * @function MyComponent
 * @access Public
 * @description Component
 */
export function MyComponent() {

    const handleClickBudget = (e: React.MouseEvent) => {
        console.log(e.target.closest('.request_quote').querySelector('hiddenSection'));
    }

    return (
        <div>
            <section className={`${styles.request_quote} limit-container`}>
                <button className="f-size-20" onClick={handleClickBudget}><b>CLICK HERE</b></button>
                <div className={styles.hiddenSection}></div>
            </section>
        </div>
    );
}

What should i do?

Germano
  • 358
  • 1
  • 2
  • 13
  • 3
    Does this answer your question? [Specifying onClick event type with Typescript and React.Konva](https://stackoverflow.com/q/45089866) -- basically, change type of `e` to `React.MouseEvent`. Then: ```(e.target as HTMLButtonElement).closest(`.${styles.request_quote}`)!.querySelector(`.${styles.hiddenSection}`)``` – brc-dd Aug 02 '21 at 12:34

1 Answers1

0
function getParentByCss<T extends HTMLElement>(e: HTMLElement, className: string) {

    const hasClass = (e) => e.classList.contains(className);

    const f = (e) => {
        if(!e) return null;
        if (hasClass(e)) return e as T;
        return f(e.parentElement);
    }

    return f(e);
}
citykid
  • 9,916
  • 10
  • 55
  • 91