Issue
First of all Greeting from my side I am beginner in Reactjs and I am learning a new hook called useRef() hook. Basically I am trying to fetch the content of every element present in my div using useRef Hook. In my code I need to access the content of only p tag how can I achieve it ? This is my Code :-
import React,{useRef} from 'react'
function FormData() {
const getAllData = useRef(null)
const onClickHandler = () =>{
console.log(getAllData.current)
}
return (
<div ref={getAllData} >
<h1>UseRef Tutorial</h1>
<p>Abhishek Poddar</p>
<input type="email" placeholder='Enter the Email' />
<br></br>
<br></br>
<input type="password" placeholder='Enter the Password' />
<br></br>
<br></br>
<button onClick={onClickHandler}>Click Me</button>
</div>
)
}
export default FormData
Solution
getAllData.current
now is an element object
. list of properties and methods
you can access its children via children
property.
const onClickHandler = () => {
const list = getAllData.current.children;
for (const e of list) {
if (e.tagName === "P") {
console.log(e.textContent);
}
}
};
Answered By - Hao.Le Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.