Skip to content

Commit eec035c

Browse files
committed
Extract mergeRefs into its own function
1 parent 2eef9fe commit eec035c

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed

src/js/components/DualListBox.jsx

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import refShape from '../shapes/refShape';
1212
import optionsShape from '../shapes/optionsShape';
1313
import valueShape from '../shapes/valueShape';
1414
import indexesOf from '../util/indexesOf';
15+
import mergeRefs from '../util/mergeRefs';
1516
import swapOptions from '../util/swapOptions';
1617
import { ALIGNMENTS, KEYS } from '../constants';
1718
import Action from './Action';
@@ -708,21 +709,6 @@ function DualListBox(props) {
708709
// Wrap event handlers with a controlKey reference
709710
const wrapHandler = (handler) => ((event) => handler(event, controlKey));
710711

711-
// Set both internal ref and property ref
712-
/* eslint-disable no-param-reassign */
713-
const makeRef = (c) => {
714-
ref.current = c;
715-
716-
if (refProp !== null) {
717-
if (typeof refProp === 'function') {
718-
refProp(c);
719-
} else {
720-
refProp.current = c;
721-
}
722-
}
723-
};
724-
/* eslint-enable no-param-reassign */
725-
726712
return (
727713
<ListBox
728714
actions={alignActions === ALIGNMENTS.TOP ? actions : null}
@@ -731,7 +717,7 @@ function DualListBox(props) {
731717
disabled={disabled}
732718
filterValue={filter[controlKey]}
733719
id={id}
734-
inputRef={makeRef}
720+
inputRef={mergeRefs([ref, refProp])}
735721
selections={selections[controlKey]}
736722
showNoOptionsText={showNoOptionsText}
737723
onDoubleClick={wrapHandler(onOptionDoubleClick)}

src/js/util/mergeRefs.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Merge and set multiple refs for a component.
3+
*
4+
* @param {React.MutableRefObject[]} refs
5+
*
6+
* @return {Function}
7+
*/
8+
function mergeRefs(refs) {
9+
return (c) => {
10+
/* eslint-disable no-param-reassign */
11+
refs.forEach((ref) => {
12+
if (ref !== null) {
13+
if (typeof ref === 'function') {
14+
ref(c);
15+
} else {
16+
ref.current = c;
17+
}
18+
}
19+
});
20+
/* eslint-enable no-param-reassign */
21+
};
22+
}
23+
24+
export default mergeRefs;

0 commit comments

Comments
 (0)