Skip to content

Accept Ref Objects as Refs? #10581

@sebmarkbage

Description

@sebmarkbage

Reason React uses first class OCaml refs to store mutable values (instead of on this instances).

These are basically just an object with a mutable contents property. These can be updated with callback refs n => ref.contents = n but it would be a nice convenience feature to just have that built-in.

We could also make these first class objects on isomorphic React.

React.createRef = () => ({ contents: null });
class Foo extends React.Component {
  state = {
    myDiv: React.createRef()
  };
  componentDidMount() {
    if (myDiv.contents) {
      myDiv.contents.focus();
    }
  }
  render() {
    return <div ref={this.state.myDiv} />;
  }
}

Basically the implementation would just be:

if (typeof ref === 'function') {
  ref(newValue);
} else if (typeof ref === 'object') {
  ref.contents = newValue;
} else if (typeof ref === 'string') {
  owner.refs[ref] = newValue;
}

This is something that needs to be implemented in the core runtime and not as part of any particular component API since refs cross that boundary.

cc @adamjernst

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions