Skip to content
This repository was archived by the owner on Nov 9, 2024. It is now read-only.

Commit a6c060c

Browse files
authored
Singleton now works when Tippys are added (#295)
* Singleton now works when Tippys are added * Don’t setInstances if singleton is destroyed Co-authored-by: Karl O’Keeffe <karl.okeeffe@coremont.com>
1 parent 3290d28 commit a6c060c

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

src/useSingleton.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,12 +109,24 @@ export default function useSingletonGenerator(createSingleton) {
109109
)
110110
) {
111111
mutableBox.children.push(data);
112+
113+
if (mutableBox.instance && !mutableBox.instance.state.isDestroyed) {
114+
mutableBox.instance.setInstances(
115+
mutableBox.children.map(child => child.instance),
116+
);
117+
}
112118
}
113119
},
114120
cleanup(instance) {
115121
mutableBox.children = mutableBox.children.filter(
116122
data => data.instance !== instance,
117123
);
124+
125+
if (mutableBox.instance && !mutableBox.instance.state.isDestroyed) {
126+
mutableBox.instance.setInstances(
127+
mutableBox.children.map(child => child.instance),
128+
);
129+
}
118130
},
119131
};
120132

test/useSingleton.test.js

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, {useState} from 'react';
22
import Tippy, {useSingleton} from '../src';
33
import TippyHeadless, {
44
useSingleton as useSingletonHeadless,
@@ -169,6 +169,52 @@ describe('disabled prop', () => {
169169
});
170170
});
171171

172+
it('when new Tippys are added to DOM, they are registered with singleton', () => {
173+
const TippyCreator = ({target}) => {
174+
const [isTippyAdded, setIsTippyAdded] = useState(false);
175+
176+
return (
177+
<div>
178+
<button onClick={() => setIsTippyAdded(true)} data-testid="add-tippy" />
179+
{isTippyAdded && (
180+
<Tippy content="a" singleton={target}>
181+
<button data-testid="a" />
182+
</Tippy>
183+
)}
184+
</div>
185+
);
186+
};
187+
188+
function App() {
189+
const [source, target] = useSingleton();
190+
191+
return (
192+
<>
193+
<Tippy
194+
onCreate={onCreate}
195+
singleton={source}
196+
trigger="click"
197+
hideOnClick={false}
198+
/>
199+
<TippyCreator target={target} />
200+
</>
201+
);
202+
}
203+
204+
const {getByTestId} = render(<App />);
205+
206+
const addTippyButton = getByTestId('add-tippy');
207+
208+
fireEvent.click(addTippyButton);
209+
210+
const buttonA = getByTestId('a');
211+
212+
fireEvent.click(buttonA);
213+
214+
expect(instance.state.isVisible).toBe(true);
215+
expect(instance.props.content.textContent).toBe('a');
216+
});
217+
172218
describe('useSingleton headless mode', () => {
173219
function App() {
174220
const [source, target] = useSingletonHeadless();

0 commit comments

Comments
 (0)