To traverse a React tree and get the states of components is to use React Refs with a method to expose state in class components.
Solution: Using Ref to Access Component State (For Class Components)
Since React does not provide a built-in way to access component states externally, you need to explicitly expose them via a method.
Implementation:
import React, { Component, createRef } from "react";
class ChildComponent extends Component {
state = {
message: "Hello from Child",
};
getState = () => {
return this.state; // Exposing state via a method
};
render() {
return <p>{this.state.message}</p>;
}
}
class App extends Component {
childRef = createRef();
componentDidMount() {
if (this.childRef.current) {
console.log("Child State:", this.childRef.current.getState()); // Accessing state
}
}
render() {
return <ChildComponent ref={this.childRef} />;
}
}
export default App;