Reputation: 103
I have object that returns the icon object based on the icon name. For proper MaterialUI icon name, the function returns the proper icon object. For incorrect name, this function should returns error icon. My code doesn't work. When I put incorrect icon name, I have error stack on browser. How can I catch this exception i JSX?
import React from 'react';
import ErrorIcon from '@material-ui/icons/Error';
import * as Icons from '@material-ui/icons';
export default function DynamicIcon({iconName}) {
try {
let Icon = Icons[iconName];
return (<Icon />);
} catch (e) {
return (<ErrorIcon color="error" />);
}
}
Upvotes: 1
Views: 227
Reputation: 15841
There is a nice example on React Blog:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Then, in JSX:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
This should avoid to implement error check for every compoent. You can also wrap your entire app in this component.
Upvotes: 1
Reputation: 8947
You can check whether an icon exists before you create an element like so without needing to catch an error.
export default function DynamicIcon({iconName}) {
const Icon = Icons[iconName];
return Icon ? <Icon /> : <ErrorIcon color="error" />;
}
This checks if Icons[iconName]
is truthy, i.e. whether an icon with the name exists, and returns the Icon element, else returns the ErrorIcon.
Upvotes: 0