Saswat
Saswat

Reputation: 339

How to access a dynamically created DOM element in react

This is something similar to what i have excluding any others divs:

import React from "react";

export default function Post({post}) {

<div className="postDesc">
    {post.sanitizedHtml} //This contains p tag inside
</div>

    )
}

This post prop is coming from an api and post.sanitizedHtml basically contains raw html that has tags such as p ,h2 etc.

What i want is to access the p tag that is inside post.sanitizedHtml so that i can use the javascript property .textContent on it and extract the information.

But i think there is no method in react like document.querySelector or document.getElementBy:Id/Classname

Also i think i can't use refs because the data is coming in dynamically and i cant write ref={something} as a prop

So what should i do to access the p tag that is there inside the post.sanitizedHtml ?

Your fast response is appreciated.

Upvotes: 0

Views: 3843

Answers (2)

Abhishek Sharma
Abhishek Sharma

Reputation: 183

By setting a ref on the outer div, you can access its child nodes and change their properties as you like.

Read more about Child Nodes

import React, { useRef, useEffect } from 'react';

export const Post = ({post}) => {
  
  const containerRef = useRef(null);
  
  //Let's Change something inside the post
  useEffect(() => {
    if(!post.sanitizedHtml || !containerRef.current) return;
    
    const container = containerRef.current;
    const childNodes = container.childNodes; //This will be a list of child nodes
    /* let's say 0th element of childNodes is a p tag */
    childNodes[0].innerText = "Hey I changed Something";
    
    
  }, [post, containerRef])
  
  return(
    <div className="postDesc" ref={containerRef}>
      {post.sanitizedHtml}
    </div>
  )
}

Upvotes: 2

briang
briang

Reputation: 91

In your situation, are you able to create an element with javascript and assign the sanitizedHtml to it, then just reference it from the newly created element?

const myElement = document.createElement("DIV"); 
myElement.innerHTML = post.santizedHtml;

then lookup from myElement

Upvotes: 1

Related Questions