Skip to content

Commit

Permalink
use native JS private properties
Browse files Browse the repository at this point in the history
  • Loading branch information
Macil committed Apr 26, 2024
1 parent 073d77b commit be1f3b8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@ import React from 'react';
import MultiRef from 'react-multi-ref';

class Foo extends React.Component {
_itemRefs = new MultiRef();
#itemRefs = new MultiRef();

render() {
// Make a 5-item array of divs with keys 0,1,2,3,4
const items = new Array(5).fill(null).map((n, i) =>
<div key={i}>
<input type="text" ref={this._itemRefs.ref(i)} />
<input type="text" ref={this.#itemRefs.ref(i)} />
</div>
);
return (
<div>
<button onClick={this._onClick}>Alert</button>
<button onClick={this.#onClick}>Alert</button>
{ items }
</div>
);
}

_onClick = () => {
#onClick = () => {
const parts = [];
this._itemRefs.map.forEach(input => {
this.#itemRefs.map.forEach(input => {
parts.push(input.value)
});
alert('all inputs: ' + parts.join(', '));
Expand Down
10 changes: 5 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@ type RefFn<V> = (value: V|null) => mixed;
export default class MultiRef<K,V> {
map: Map<K,V> = new Map();

_refFns: Map<K,RefFn<V>> = new Map();
#refFns: Map<K,RefFn<V>> = new Map();

ref(key: K): RefFn<V> {
const refFn = this._refFns.get(key);
const refFn = this.#refFns.get(key);
if (refFn) {
return refFn;
} else {
const refFn: RefFn<V> = value => {
if (value == null) {
// Support for React <=18, which cleans up ref functions by calling them
// with null.
this._refFns.delete(key);
this.#refFns.delete(key);
this.map.delete(key);
} else {
this._refFns.set(key, refFn);
this.#refFns.set(key, refFn);
this.map.set(key, value);
// React 19+ cleanup support
return () => {
this._refFns.delete(key);
this.#refFns.delete(key);
this.map.delete(key);
};
}
Expand Down

0 comments on commit be1f3b8

Please sign in to comment.