Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the element that was clicked in functional component in React

I’m new to React and can’t get the clicked element.

"this" in functional component doesn’t work

function Test(data) {

    function getElement() {

    }
    return (
        <div>
            {data.map((option: any, index: any) => (
            <Text
                key={index}
                onClick={() => getElement()}
              >
                {option}
              </Text>
             ))}
         </div>
    )
}

there are several elements in the data that I want to switch one by one, changing the class ‘active’, but it is not possible to get the element that was clicked

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Be sure to pass the event to your click handler:

function Test(data) {
    const handleClick = e => {
        const el = e.target
        console.log(el)
    }

    return (
        <div>
            {data.map((option: any, index: any) => (
                <Text
                    key={index}
                    onClick={handleClick}
                >
                    {option}
                </Text>
            ))}
        </div>
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading