Accepted answer

This is an intriguing question! At a high level, the problem is that React isn't catching the 'change' event that bubbled up to the top-level component when you clicked the checkbox, because it wasn't instantiated yet on the client side. Your half-solution handles this by manually simulating a call to onChange. I started thinking that you might need to queue onChange events... but then I realized that React already has everything you need.

The "three-quarters" solution is to simply rename syncStateFromDOM to componentDidMount, and don't even bother calling it manually. As per the docs, in the most recent versions of React, componentDidMount is only called in the browser, and it's a lifecycle callback for after the component mounts (i.e. when React.render is about to return). It's the perfect place for your use case. See:

That solves your problem of code external to the component itself! But there's still state-setting going on after the original render takes place. Unfortunately, I think this is fundamentally the way React works - in order to be able to match up existing DOM nodes to refs, each component needs to be fully mounted first. But an extra Virtual DOM diff is a small price to pay, since it's designed to be lightning-quick.

Hope this helps!

Related Query

More Query from same tag