简体   繁体   中英

How to access inner content of div or any element in reactjs using useRef Hook?

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

Ok so if you just need to access the P tag. then you can modify your OnlickHandler something like this.

const onClickHandler = () => {
 console.log(getAllData.current.children[1].innerText);
};

you can access the current elements' child properties by going through its indexes. So in that case your P tag lies on the 1st index so you can just do and you'll get the P tag.

.children[index]

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);
      }
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM