Creating this issue to track https://github.com/facebook/react/pull/11555. I intend to close the PR as it's outdated, but we probably want to turn it into a real RFC and potentially get it in during 16.x.
As an alternative to adding new React API, could this just be moved into userspace?
In the OP from https://github.com/facebook/react/pull/11555, we could amend the example as:
import createRef from 'create-react-ref';
class MyComponent extends React.Component {
render() {
return <div><input type="text" ref={createRef(this, 'div')} /></div>;
}
componentDidMount() {
this.refs.div.value.focus();
}
}
As a really dumb implementation:
export default function createRef(inst, refName) {
if (!inst.refs) {
inst.refs = {};
}
if (!inst.stringRefFuncs) {
inst.stringRefFuncs = {};
}
if (!inst.stringRefFuncs[refName]) {
inst.stringRefFuncs[refName] = c => {
inst.refs[refName] = c;
};
}
return inst.stringRefFuncs[refName];
}
This may not literally work as-is given that I think touching this.refs is weird, but it still seems like this API could live outside of React core.
It would even be possible to write a Babel transform to do this automatically.
Alternatively:
function createRef() {
function ref(c) {
ref.value = c;
}
return ref;
}
I don't know if the edge cases exactly match https://github.com/facebook/react/pull/11555, but this can live in userspace, and doesn't require any changes to the reconciler.
Unless per https://github.com/facebook/react/pull/11555#issuecomment-344389679 and https://github.com/facebook/react/pull/11555#issuecomment-355027152, the intention is for users of "vanilla" function refs to migrate to this scheme as well.
What is the benefit of moving it out? File size? (Presumably it would be small enough and the vast majority of libs would need it anyway.)
I'm not sure. I didn't quite follow the conclusion from https://github.com/facebook/react/pull/11555#issuecomment-344384871.
Is the idea that, going forward, most ref users will use createRef rather than attaching a callback ref? Or is this a convenience thing for people currently using string refs, but that going forward people should still mostly use callback refs?
If it's a convenience thing, it seems like putting this in user space reduces the React API surface area.
I think the idea is that most people will use createRef, and callback refs are relegated to being a power user feature since they鈥檙e more cumbersome and harder to explain.
That makes sense. Thanks!
What is the benefit of moving it out?
Maybe it will be less attractive for use, because it's another dependency? In this case, it's not so obvious what will be preferable for use. That makes sense?
@strayiker use rfc for comments
Shipped in 16.3
Most helpful comment
I think the idea is that most people will use
createRef, and callback refs are relegated to being a power user feature since they鈥檙e more cumbersome and harder to explain.