I'm rendering in index.js the following main component:
export default function Home() {
return (
<Main/>
)
}
Where Main component is defined as:
import React from "react";
export default class Main extends Child {
constructor(props) {
super(props);
}
async componentDidMount() {
if (this.state.ready) {
console.log('Parent ready'); // This is NOT called!
} else {
console.log('Parent mounted'); // This is called fine.
}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.ready != this.state.ready) {
console.log('Parent updated'); // This is NOT called!
}
}
render() {
return (
<div>
<Child/>
</div>
)
}
}
And Child component is:
export default class Child extends React.Component {
constructor(props) {
super(props);
this.state = {ready: false};
}
async componentDidMount() {
if (!this.state.ready) {
// I'm loading some dynamic libraries here...
// ...then set the state as ready.
this.setState({ready: true});
}
}
componentDidUpdate(prevProps, prevState) {
if (prevState.ready != this.state.ready) {
console.log('Child ready'); // This is called.
}
}
render() {
if (this.state.ready) {
return (
<div>Loaded.</div>
)
} else {
return (
<div>Loading...</div>
)
}
}
}
After run, console log produces the following lines:
Parent mounted
Child ready
My problem is that the parent is that never notified of child's ready state (componentDidMount()), neither parent's componentDidUpdate is called.
How do I notify parent's class that the child is in ready state to perform certain actions (in parent component)?
I've already tried:
- Referencing
Mainwithref="child"(inindex.js) to reference parent from child instance, but had an error (Function components cannot have string refs. We recommend using useRef() instead). - Calling
super()from Child class in different ways (such as calling hook manually). - Used
const mainRef = useRef();orthis.mainRef = useRef();in different ways, but without success (more errors: Error: Invalid hook call).
Is there any easier way?