Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- Increased column width on `EuiTableHeaderCellCheckbox` to prevent `EuiCheckbox`'s focus ring from getting clipped in `EuiBasicTable` ([#2770](https://github.com/elastic/eui/pull/2770))
- Fixed the display of `EuiButton` within `EuiControlBar` when `fill={true}` to be more consistent with other buttons ([#2781](https://github.com/elastic/eui/pull/2781))
- Fixed `EuiFormControlLayout` from overwriting className for `prepend` nodes. ([#2796](https://github.com/elastic/eui/pull/2796))
- Fixed `useRenderToText` and `EuiButtonToggle` from attempting state updates on unmounted components ([#2797](https://github.com/elastic/eui/pull/2797))

**Deprecations**

Expand Down
31 changes: 22 additions & 9 deletions src/components/inner_text/render_to_text.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import React, { ReactNode, useEffect } from 'react';
import React, { ReactNode, useCallback, useEffect, useRef } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { useInnerText } from './inner_text';

export function useRenderToText(node: ReactNode, placeholder = ''): string {
const [ref, text] = useInnerText(placeholder);
const hostNode = useRef<Element | null>(null);

const onUnmount = () => {
if (hostNode.current) {
unmountComponentAtNode(hostNode.current);
hostNode.current = null;
}
};

const setRef = useCallback(
(node: Element | null) => {
if (hostNode.current) {
ref(node);
}
},
[ref]
);

useEffect(() => {
const hostNode = (document.createDocumentFragment() as unknown) as Element;
render(<div ref={ref}>{node}</div>, hostNode);
hostNode.current = (document.createDocumentFragment() as unknown) as Element;
render(<div ref={setRef}>{node}</div>, hostNode.current);
return () => {
// since we're in React's lifecycle via `useEffect`, wait a
// tick to escape otherwise React performs multiple unmounts 🤷
requestAnimationFrame(() => {
unmountComponentAtNode(hostNode);
});
onUnmount();

Choose a reason for hiding this comment

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

👍 it's nice that the RAF trick is no longer required

};
}, [node, ref]);
}, [node, setRef]);

return text || placeholder;
}