PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

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

 October 15, 2022     dom, javascript, react-hooks, reactjs     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing