Vamsi
Vamsi

Reputation: 392

How to save an id in a variable and show it in console in react

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

Answers (1)

Sifat Haque
Sifat Haque

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

Related Questions