Home > Software design >  Getting the element that was clicked in functional component in React
Getting the element that was clicked in functional component in React

Time:03-18

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

CodePudding user response:

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>
    )
}
  • Related