Skip to content

Instantly share code, notes, and snippets.

@IARI
Created May 8, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IARI/69d3c941f3549362493aa7f59de84e0a to your computer and use it in GitHub Desktop.
Save IARI/69d3c941f3549362493aa7f59de84e0a to your computer and use it in GitHub Desktop.
import react.*
import react.dom.p
import react.dom.h3
import kotlinext.js.jsObject
import styled.styledDiv
val App = functionalComponent<RProps> {
errorBoundary {
p {
+"Test"
throw RuntimeException("whatever")
}
}
}
external interface ErrorBoundaryState : RState {
var error: Throwable?
}
class ErrorBoundary : RComponent<RProps, ErrorBoundaryState>() {
override fun componentDidCatch(error: Throwable, info: RErrorInfo) {
console.log("ErrorBoundary encountered error:", error)
}
override fun RBuilder.render() {
val error = state.error
if (error != null) {
styledDiv {
h3 {
+"Something went wrong"
}
p {
+error.toString()
}
}
} else props.children()
}
companion object : RStatics<RProps, ErrorBoundaryState, ErrorBoundary, Nothing>(ErrorBoundary::class) {
init {
getDerivedStateFromError = {
jsObject<ErrorBoundaryState> {
error = it
}
}
}
}
}
fun RBuilder.errorBoundary(handler: RBuilder.() -> Unit): ReactElement = child(ErrorBoundary::class, handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment