How to catch different events from dom elements (div/img/input) and how to interact(get/set attributes,styles,classes) with them with react js?

Viewed 50

for example we have this button and this div

<button onClick={test_func}>
</button>
<div class="js_test">
</div>

in jquery we do so !

$(document).on('click', '.js_test', fu
    //code
});
$(document).on('EVENT_TYPE', 'ELEMENT_DOM', function(evt) {});

$('ELEMENT_DOM').css();
$('ELEMENT_DOM').attr();
$('ELEMENT_DOM').addClass();

in js you can catch all events by class or id

.js_test

so how is it like in React.js

test_func() {
    //inside here i need to do something with div .js_test 
    // to set text, add new class, set new css style like color: 'red' for example
}
1 Answers

You can receive the event in the function, and use e.target (.nextElementSibling to target the div close to the button) Or you can use the useRef hook, and use ref.current

import { useState } from "react";
import { useRef } from "react"

function Teste(){
    const ref = useRef();
    const [darkMode, setDarkMode] = useState(false);

    function AlterWithEDotTarget(e){
        e.target.nextElementSibling.innerHTML = "WAS ALTERED!"
    }

    function AlterWithUseRef(){
        ref.current.innerHTML  = "WAS ALTERED!";
    }

    function ToggleDarkMode() {
        setDarkMode(!darkMode)
    }

    return (<>
                <button onClick={AlterWithEDotTarget}>Alter With e.target</button>
                <div>Will be altered with e.target {darkMode ? "DarkMode ON" : ""}</div>

                <br/>
                <br/>

                <button onClick={AlterWithUseRef}>Alter With useRef</button>
                <div ref={ref}>Will be altered with useRef {darkMode ? "DarkMode ON" : ""}</div>

                <br/>
                <br/>

                <button onClick={ToggleDarkMode}>Toggle Dark Mode</button>
            </>)

}

export default Teste

EDIT

In react things are different than jQuery, i added an example targeting multiple elements, you do it using state, and binding the state to the elements, and when the state changes, the elements change as well

Related