Thomas.lin
Thomas.lin

Reputation: 440

How the get the FiberNode in React Hook?

I want to get the Fiber node in Hook,But don't know how to ?

import React from 'react';

export default function App() {
  // get the FiberNode in this Component
  return <div></div>;
}

Upvotes: 4

Views: 2474

Answers (2)

jsDev
jsDev

Reputation: 326

The easiest way to take a look at the FiberNode instance is by using html selector.

  1. Open Dev Tools in your browser
  2. Type the html selector of your component, in my case document.querySelector(".card").__reactFiber and hit cmd + Space and Tab buttons to autocomplete - becouse each FiberNode has uniq id.

In my case whole selector looks like this document.querySelector(".card").__reactFiber$n9r3t0wnc2.

FiberNode is a part of React Fiber tree (Linked List data structure) and contains all internal information about your component such as: prev and next states, props, list of hooks an so on.

enter image description here

You can also check it inside react useEffect hook.

    useEffect(() => {
        const el = document.querySelector(".card");
        // @ts-expect-error just for the sake of example
        const list = Object.keys(el);
        const keyIdx = list.findIndex((k) => k.indexOf("__reactFiber"));
        // @ts-expect-error just for the sake of example
        console.log(el[list[keyIdx]]);
    }, []);

enter image description here

Upvotes: 1

Thomas.lin
Thomas.lin

Reputation: 440

I found the way, document.getElementById("root")._reactRootContainer._internalRoot.current

Upvotes: 2

Related Questions