Let me start off by saying I understand you should never use refs.
With that said, I think in my scenario it is very valid. Specifically I am using a window.onscroll handler and cannot simply change props in the onscroll handler. Changing state or props in an onscroll handler rerenders child componentsfar too often, which causes way too much lag.
Hence since my scenario only requires setting the style of an element on scroll, (i.e. I make something sticky to the top of page when it is scrolled out of view), I get 0 lag by simply setting this.refs.myelement.style.position = 'fixed'
My problem is that I am currently doing:
this.refs.childelement.refs.childschildelement.refs.childschildschildselement.refs.style.position = 'fixed'
Basically I have my onscroll handler
3 parents abvoe on the actual element I want to style.
My page consists of a List
component. This consists of ReadOnlyOrEditable
components. Editable components are RichTextEditors
which have a Toolbar
Component. It is this Toolbar
that I need to set the position to fixed when a window scroll event occurs.
Hence on a page I'll have some 10 ReadOnlyOrEditable
components, of which maybe 5 are RichTextEditors
, each having a Toolbar
.
The toolbar has buttons like italics, bold, etc.
When the user scrolls down, we don't want the user to have to scroll back up if the toolbar goes out of view. I.e. so we want to set the position to be fixed if the toolbar goes out of view so that the user can hit italics / bold / etc. immediately.
So how do I make this nicer without having to pass refs from the top down? The way I currently have it is very ugly...
I prefer to keep the onscroll handler close to the location of the list because having window.onscroll handlers in each Toolbar component implies I am setting multiple window.scroll handlers which is unnecesary work on the browser.
Any suggestions is gladly welcome.