function BadgeComponent({status}) {
const statusColorMapper = {
0: {text: 'FAILURE', color: 'danger'},
1: {text: 'SUCCESS', color: 'success'},
2: {text: 'PENDING', color: 'secondary'},
};
const statusObject = statusColorMapper[status];
const className = `badge badge-${statusObject.color}`;
return (
<span className={className}>
{statusObject.text}
</span>
);
}
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
this.resetState = this.resetState.bind(this);
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log(error, errorInfo);
}
resetState(){
this.props.resetState();
this.setState({hasError: false});
}
render() {
if (this.state.hasError) {
return (
<div>
<span className="badge badge-info">
Something Went Wrong
</span>
<button onClick={this.resetState}>Click to Reset</button>
</div>
);
}
return this.props.children;
}
}
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 0
}
this.updateStatus = this.updateStatus.bind(this);
this.resetState = this.resetState.bind(this);
}
updateStatus() {
console.log('clicked');
this.setState((state, props) => {
return {status: state.status + 1};
})
}
resetState() {
this.setState({status: 0});
}
render() {
return (
<div className="d-flex flex-column w-50">
<ErrorBoundary resetState={this.resetState}>
<BadgeComponent status={this.state.status} />
<button className="btn btn-sm btn-primary mt-2"
onClick={this.updateStatus}>
Update Status
</button>
</ErrorBoundary>
</div>
);
}
}
ReactDOM.render(<Application />, document.getElementById('app'));
View Compiled