Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC] Add a new React.createRef() API for ref objects #11555

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion packages/react-dom/src/__tests__/ReactComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ describe('ReactComponent', () => {
ReactTestUtils.renderIntoDocument(<Parent child={<span />} />);
});

it('should support new-style refs', () => {
it('should support callback-style refs', () => {
var innerObj = {};
var outerObj = {};

Expand Down Expand Up @@ -185,6 +185,49 @@ describe('ReactComponent', () => {
expect(mounted).toBe(true);
});

it('should support object-style refs', () => {
var innerObj = {};
var outerObj = {};

class Wrapper extends React.Component {
getObject = () => {
return this.props.object;
};

render() {
return <div>{this.props.children}</div>;
}
}

var mounted = false;

class Component extends React.Component {
constructor() {
super();
this.innerRef = React.createRef();
this.outerRef = React.createRef();
}
render() {
var inner = <Wrapper object={innerObj} ref={this.innerRef} />;
var outer = (
<Wrapper object={outerObj} ref={this.outerRef}>
{inner}
</Wrapper>
);
return outer;
}

componentDidMount() {
expect(this.innerRef.value.getObject()).toEqual(innerObj);
expect(this.outerRef.value.getObject()).toEqual(outerObj);
mounted = true;
}
}

ReactTestUtils.renderIntoDocument(<Component />);
expect(mounted).toBe(true);
});

it('should support new-style refs with mixed-up owners', () => {
class Wrapper extends React.Component {
getTitle = () => {
Expand Down
40 changes: 39 additions & 1 deletion packages/react-dom/src/__tests__/ReactErrorBoundaries-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,7 @@ describe('ReactErrorBoundaries', () => {
expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
});

it('resets refs if mounting aborts', () => {
it('resets callback refs if mounting aborts', () => {
function childRef(x) {
log.push('Child ref is set to ' + x);
}
Expand Down Expand Up @@ -981,6 +981,44 @@ describe('ReactErrorBoundaries', () => {
]);
});

it('resets object refs if mounting aborts', () => {
let childRef = React.createRef();
let errorMessageRef = React.createRef();

var container = document.createElement('div');
ReactDOM.render(
<ErrorBoundary errorMessageRef={errorMessageRef}>
<div ref={childRef} />
<BrokenRender />
</ErrorBoundary>,
container,
);
expect(container.textContent).toBe('Caught an error: Hello.');
expect(log).toEqual([
'ErrorBoundary constructor',
'ErrorBoundary componentWillMount',
'ErrorBoundary render success',
'BrokenRender constructor',
'BrokenRender componentWillMount',
'BrokenRender render [!]',
// Handle error:
// Finish mounting with null children
'ErrorBoundary componentDidMount',
// Handle the error
'ErrorBoundary componentDidCatch',
// Render the error message
'ErrorBoundary componentWillUpdate',
'ErrorBoundary render error',
'ErrorBoundary componentDidUpdate',
]);
expect(errorMessageRef.value.toString()).toEqual('[object HTMLDivElement]');

log.length = 0;
ReactDOM.unmountComponentAtNode(container);
expect(log).toEqual(['ErrorBoundary componentWillUnmount']);
expect(errorMessageRef.value).toEqual(null);
});

it('successfully mounts if no error occurs', () => {
var container = document.createElement('div');
ReactDOM.render(
Expand Down
6 changes: 5 additions & 1 deletion packages/react-reconciler/src/ReactChildFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<*> {

function coerceRef(current: Fiber | null, element: ReactElement) {
let mixedRef = element.ref;
if (mixedRef !== null && typeof mixedRef !== 'function') {
if (
mixedRef !== null &&
typeof mixedRef !== 'function' &&
typeof mixedRef !== 'object'
) {
if (element._owner) {
const owner: ?Fiber = (element._owner: any);
let inst;
Expand Down
3 changes: 2 additions & 1 deletion packages/react-reconciler/src/ReactFiber.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import type {ReactElement, Source} from 'shared/ReactElementType';
import type {
RefObject,
ReactCall,
ReactFragment,
ReactPortal,
Expand Down Expand Up @@ -95,7 +96,7 @@ export type Fiber = {|

// The ref last used to attach this node.
// I'll avoid adding an owner field for prod and model that as functions.
ref: null | (((handle: mixed) => void) & {_stringRef: ?string}),
ref: null | (((handle: mixed) => void) & {_stringRef: ?string}) | RefObject,

// Input is the data coming into process this fiber. Arguments. Props.
pendingProps: any, // This type will be more specific once we overload the tag.
Expand Down
40 changes: 27 additions & 13 deletions packages/react-reconciler/src/ReactFiberCommitWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,22 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
function safelyDetachRef(current: Fiber) {
const ref = current.ref;
if (ref !== null) {
if (__DEV__) {
invokeGuardedCallback(null, ref, null, null);
if (hasCaughtError()) {
const refError = clearCaughtError();
captureError(current, refError);
if (typeof ref === 'function') {
if (__DEV__) {
invokeGuardedCallback(null, ref, null, null);
if (hasCaughtError()) {
const refError = clearCaughtError();
captureError(current, refError);
}
} else {
try {
ref(null);
} catch (refError) {
captureError(current, refError);
}
}
} else {
try {
ref(null);
} catch (refError) {
captureError(current, refError);
}
ref.value = null;
}
}
}
Expand Down Expand Up @@ -162,20 +166,30 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
const ref = finishedWork.ref;
if (ref !== null) {
const instance = finishedWork.stateNode;
let instanceToUse;
switch (finishedWork.tag) {
case HostComponent:
ref(getPublicInstance(instance));
instanceToUse = getPublicInstance(instance);
break;
default:
ref(instance);
instanceToUse = instance;
}
if (typeof ref === 'function') {
ref(instanceToUse);
} else {
ref.value = instanceToUse;
}
}
}

function commitDetachRef(current: Fiber) {
const currentRef = current.ref;
if (currentRef !== null) {
currentRef(null);
if (typeof currentRef === 'function') {
currentRef(null);
} else {
currentRef.value = null;
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion packages/react/src/React.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import assign from 'object-assign';
import ReactVersion from 'shared/ReactVersion';
import {enableReactFragment} from 'shared/ReactFeatureFlags';

import {createRef} from './ReactCreateRef';
import {Component, PureComponent, AsyncComponent} from './ReactBaseClasses';
import {forEach, map, count, toArray, only} from './ReactChildren';
import ReactCurrentOwner from './ReactCurrentOwner';
Expand All @@ -31,7 +32,7 @@ const REACT_FRAGMENT_TYPE =
Symbol.for('react.fragment')) ||
0xeacb;

var React = {
const React = {
Children: {
map,
forEach,
Expand All @@ -40,6 +41,7 @@ var React = {
only,
},

createRef,
Component,
PureComponent,
unstable_AsyncComponent: AsyncComponent,
Expand Down
19 changes: 19 additions & 0 deletions packages/react/src/ReactCreateRef.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing @flow annotation?


import type {RefObject} from 'shared/ReactTypes';

// an immutable object with a single mutable value
export function createRef(): RefObject {
const refObject = {
value: null,
};
if (__DEV__) {
Object.seal(refObject);
}
return refObject;
}
4 changes: 4 additions & 0 deletions packages/shared/ReactTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,7 @@ export type ReactPortal = {
// TODO: figure out the API for cross-renderer implementation.
implementation: any,
};

export type RefObject = {|
value: any,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With input will be ref.value.value :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, I believe contents is also a property on some DOM nodes too. value makes more sense in the case of this immutable object having a mutable object representing the ref itself.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be a bit much, but what if it was element for a DOM element and component for a React component, instead of value?

|};