Home > Back-end >  Why is document.getElementsByClassName not working in react?
Why is document.getElementsByClassName not working in react?

Time:11-05

So I have this piece of Code

const desc_object = document.getElementsByClassName("singlePostDesc");
console.log(desc_object[0]);

And this is the JSX

{updateMode ? (
                        <>
                            <textarea
                                className="singlePostDescInput"
                                autoFocus={true}
                                id="desc"
                                onChange={(e) => setDesc(e.target.value)}
                                onKeyPress={(e) => key_callback(e.key)}
                            >
                                {desc}
                            </textarea>
                            <button
                                className="singlePostButton"
                                onClick={update_post_to_backend}
                            >
                                Update Post
                            </button>
                        </>
                    ) : (
                        <div className="singlePostDesc" id="descThing">
                            <ReactMarkdown children={sanitizeHtml(desc)} />
                        </div>
                    )}

But I get the result as undefined. Why? Is it because it is wrapped in a ternary operator? I am using React JS.

CodePudding user response:

In order to access DOM methods in react, you have to call this piece of code inside useEffect hook.

useEffect(() => {
  const desc_object = document.getElementsByClassName("singlePostDesc");
  if (desc_object) {
   // now you can access it here
  }

})

though the first time useEffect hooks runs getElementsByClassName will return undefined because the DOM is not mounted yet.

if you want to run this DOM query only after the component did mount, you can create a custom hook:

const useDidMountEffect = (func, deps) => {
 const didMount = useRef(false)

 useEffect(() => {
   if (didMount.current) func()
   else didMount.current = true
  }, deps)
}

and then you can use it like that:

useDidMountEffect (() => {
 const desc_object = document.getElementsByClassName("singlePostDesc");


})

UPDATE:

as comments mentioned, ideally you should not use vanilla js, you should use React Refs

  • Related