Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: wrap preview in boundary #392

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix: wrap preview in boundary
  • Loading branch information
r281GQ committed Aug 15, 2024
commit cd1d08cac40a3d7c41ba5b3bbf46d220bb5f6ba1
44 changes: 41 additions & 3 deletions packages/react-live/src/components/Live/LivePreview.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,55 @@
import React, { useContext } from "react";
import React, { useContext, Component } from "react";
import LiveContext from "./LiveContext";

type Props<T extends React.ElementType = React.ElementType> = {
Component?: T;
} & React.ComponentPropsWithoutRef<T>;

class ErrorBoundary extends Component<
{
children: React.ReactNode;
onError?: (error: Error) => void;
},
{ hasError: boolean }
> {
static getDerivedStateFromError() {
return { hasError: true };
}

constructor(props: {
children: React.ReactNode;
onError: (error: Error) => void;
}) {
super(props);
this.state = { hasError: false };
}

componentDidCatch(err: Error): void {
this.props.onError?.(err);
}

render() {
return this.props.children;
}
}

function LivePreview<T extends keyof JSX.IntrinsicElements>(
props: Props<T>
): JSX.Element;
function LivePreview<T extends React.ElementType>(props: Props<T>): JSX.Element;

function LivePreview({ Component = "div", ...rest }: Props): JSX.Element {
const { element: Element } = useContext(LiveContext);
return <Component {...rest}>{Element ? <Element /> : null}</Component>;
const { element: Element, onError, code } = useContext(LiveContext);

return (
<ErrorBoundary
key={code}
onError={(err) => {
onError(err);
}}
>
<Component {...rest}>{Element ? <Element /> : null}</Component>
</ErrorBoundary>
);
}
export default LivePreview;