Alexander
Alexander

Reputation: 1829

Console log output of element in a React app

I am trying to get an element in browser console in React production app but what I am getting is undefined or null element

    >> var el = document.querySelectorAll("div[data-reactid*='.0.0.1.0:$_player=15umwWNrNpKC=16QvOqH6ISlZ.0.5:$c457.1:$c464.$slideobject593']");
    <- undefined
    >> typeof(el)
    <- "object"
    >> el[0]
    <- undefined

I would like to inspect that element so I can create a function on it once I'd be able to retrieve that element in console log.

Am I missing something?

Upvotes: 2

Views: 2972

Answers (1)

Yuan-Hao Chiang
Yuan-Hao Chiang

Reputation: 2603

Try using refs:

import { useRef, useEffect } from 'react';

function MyComponent() {
  const myRef = useRef();

  useEffect(() => {
    console.log('element:',  myRef.current);
  }, [myRef]);

  return (
    <div>
       <h3 ref={myRef}>Hi</h3>
    </div>
  );
}

If the only goal is to print the element without having to use it in React, the easiest way is to assign an id for it for now:

return (
  <div><h3 id='myElement'>...
);

const el = document.getElementById('myElement');
console.log(el);

EDIT: Based on your query selector data it seems you're using some sort of player which may not be reachable through a ref. You can easily wrap it around a <div> and get that element:

<div id='myElement'> // or ref={myRef}
  <Player />
</div>

console.log(el.children);

Upvotes: 1

Related Questions