Skip to content

Commit 5542250

Browse files
committed
Fix invalid tag crashing issue
1 parent b3ea63f commit 5542250

File tree

1 file changed

+45
-6
lines changed

1 file changed

+45
-6
lines changed

src/components/common/MarkdownRender.tsx

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
173173
);
174174

175175
const [element, setElement] = useState<RenderedElement>(null);
176+
const [hasTagError, setHasTagError] = useState(false);
176177

177178
const applyElement = React.useMemo(() => {
178179
return throttle(250, (el: any) => {
@@ -204,18 +205,25 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
204205
return;
205206
}
206207

207-
const el = parse(editing ? html : filter(html));
208-
209-
applyElement(el);
208+
try {
209+
const el = parse(html);
210+
setHasTagError(false);
211+
applyElement(el);
212+
} catch (e) {}
210213
});
211214
}, [applyElement, editing, markdown, onConvertFinish]);
212215

213216
return (
214217
<Typography>
215218
{editing ? (
216-
<MarkdownRenderBlock className={codeTheme}>
217-
{element}
218-
</MarkdownRenderBlock>
219+
<MarkdownRenderErrorBoundary
220+
onError={() => setHasTagError(true)}
221+
hasTagError={hasTagError}
222+
>
223+
<MarkdownRenderBlock className={codeTheme}>
224+
{element}
225+
</MarkdownRenderBlock>
226+
</MarkdownRenderErrorBoundary>
219227
) : (
220228
<MarkdownRenderBlock
221229
className={codeTheme}
@@ -226,4 +234,35 @@ const MarkdownRender: React.FC<MarkdownRenderProps> = ({
226234
);
227235
};
228236

237+
type ErrorBoundaryProps = {
238+
onError: () => void;
239+
hasTagError: boolean;
240+
};
241+
class MarkdownRenderErrorBoundary extends React.Component<ErrorBoundaryProps> {
242+
state = {
243+
hasError: false,
244+
};
245+
componentDidCatch() {
246+
this.setState({
247+
hasError: true,
248+
});
249+
this.props.onError();
250+
}
251+
252+
componentDidUpdate(prevProps: ErrorBoundaryProps) {
253+
if (prevProps.hasTagError && !this.props.hasTagError) {
254+
this.setState({
255+
hasError: false,
256+
});
257+
}
258+
}
259+
260+
render() {
261+
if (this.state.hasError) {
262+
return <div>HTML 태그 파싱 실패</div>;
263+
}
264+
return this.props.children;
265+
}
266+
}
267+
229268
export default React.memo(MarkdownRender);

0 commit comments

Comments
 (0)