lucas antonio
lucas antonio

Reputation: 13

How to get id from react element

I dont understand why i cant get the id from a react object...

    function OpenNav() {
document.getElementById('lateralNav').style.animation = 'MenuEntrar 0.5s';
}

    ReactDOM.render(
<div className="barra-lateral" id="lateralNav" onClick={OpenNav()}>
,document.getElementById('root')
);

I know that im doing something wrong but i dont understand how to get the id to change the stile ! I already tried to use the script tag inside the html page but it didnt work.

Upvotes: 0

Views: 670

Answers (1)

mortezashojaei
mortezashojaei

Reputation: 452

first of all your onClick must be like this : onClick={OpenNav}

but i have better solution for your problem , and it is using Refs in Reat.

for example you can write your component like below :

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

export const MayNav = () => {
  const MyRef = useRef();

  function OpenNav() {
    MyRef.style.animation = "MenuEntrar 0.5s";
  }

  return <div onClick={OpenNav} ref={MyRef}></div>;
};

Upvotes: 1

Related Questions