React Controlled Focus
One of the biggest advantages of using React is having the possibility of a completely declarative UI, which is amazing until you run into trying to controll focus.
This is an attempt at managing
focus the same way controled components handle
The biggest difference between
value is that
focus is not actually a property of the input itself, but rather the document, in the form of the
document.activeElement. This library approaches the problem by moving the focus management outside of the individual elements up to a
<ControlledFocus> top level component.
Open the demo page to see it in action.
WARNING: The API is nowhere near 1.0 stability and it is pretty much an experiment at this point. Appretiate any feedback if I'm doing something that doesn't make sense.
Install the package:
npm intall --save react-controlled-focus
The API itself is very simple, wrap the entire application arround a
<ControlledFocus>, set up which element should have the focus via the
activeElement and handle changes in focus via the
<ControlledFocus ='input-1' =>// children components that will have the focus under-controll.<input ='input-1'/></ControlledFocus>
The value of
activeElement must match the name in
For local development:
And open http://0.0.0.0:3000/demo.html.
At this point there are a couple:
- The biggest caveat of the current implementation is that there can be only one
ControlledFocuscomponent per page;
- We still required a data attribute named
data-focus-idon each component we wish to have focus controlled;
- Depending on
data-focus-idmakes it hard to controll the focus on components that you don't own.