Reputation: 392
I am working on a React project in that I need to access an id in from html element. I tried it but it is showing some error so someone help me to resolve this issue.
This is my code
import React from 'react';
import './Test.css';
const Test = () => {
const hello = e.currentTarget.one
console.log(hello, 'test')
return (
<div id='one'>Hello World</div>
)
}
export default Test
Upvotes: 0
Views: 592
Reputation: 6067
You can use useRef
hook to get access to the div.
const { useEffect, useRef } = React;
const Test = () => {
const helloRef = useRef(null);
useEffect(() => {
console.log(helloRef.current.id);
}, []);
return (
<div id="one" ref={helloRef}>
Hello World
</div>
);
};
ReactDOM.render(
<Test/>,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Upvotes: 1