React 15 has deprecated valueLink which was a property on form elements
for expressing two-way binding between the value of the form element and a
state property of the component using the element. The recommended replacement
is to explicitly specify the value as a prop and to supply an onChange
handler instead.
It would be very tedious to write these onChange handlers for every form
element. For example:
const Profile = React;Instead of defining the handlers on the component, we can write a factory function that generates these handlers and cache them on the component instance:
{ return { const el = etarget; const value = eltype === 'checkbox' ? elchecked : elvalue; component; };} module { const cache = component__linkStateHandlers || component__linkStateHandlers = {}; return cachekey || cachekey = ;}Then we can remove all the handlers on the component and use linkState
instead:
const linkState = ; const Profile = React;You can adapt linkState to your application needs. I tend to use the
Immutable library in my projects, and I may want my handlers to support
setting a value deep inside an Immutable.Map. For example, if I have
this.state.person pointing to an Immutable.Map and I may want to set a value
at the ['name', 'last'] path using setIn. I may want linkState to look
like this when used:
const linkState = ; const Form = ReactThen I would just update linkState like so:
{ return { const el = etarget; const value = eltype === 'checkbox' ? elchecked : elvalue; component; };} module { const cache = component__linkStateHandlers || component__linkStateHandlers = {}; const cacheKey = path ? `:` : key; return cachecacheKey || cachecacheKey = ;}This createHandler function doesn't take care of every use case. For example,
changes are needed to support a <select multiple> element. I hope you find
this technique useful and easy to adapt to your applications.