Reputation: 1168
Is there a way to let a parent component know when all the child components are loaded? I am making a walkthrough in a React application. The tour steps are in my Root.js
which contains the App
component, inside this App
component are the other components. Some pages/components take a while to load but the steps continue, so my problem is that the library I am using (Shepherd.js) gives an error saying the element I attached the step to doesn't exist.
To 'fix' this I added a beforeShowPromise
which waits 2000 milliseconds before continuing:
beforeShowPromise: function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, 2000);
})
},
But ofcourse, when someone has a bad internet connection, 2000 milliseconds is too fast and I get the same error. So I would like to create some sort of function that checks if the child components where the step is attached to are loaded yet. And if they are loaded, continue with the steps. So again, my question is: is there a way to let a parent component know when all the child components are loaded?
Upvotes: 0
Views: 2293
Reputation: 849
React waits to mount all child components before calling componentDidMount
on the parent. This means that the parent component's componentDidMount
function will only be called if all children are mounted/loaded. You should never depend on a hardcoded time to make sure that the app is mounted, just use the build in lifecycle methods.
state = { mounted: false };
componentDidMount() {
this.setState({ mounted: true });
}
Or if you want to use hooks:
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
Upvotes: 2