From 5cca489acddb5e435074b4dab360c6055a834319 Mon Sep 17 00:00:00 2001 From: Johannes Schill Date: Thu, 22 Nov 2018 15:39:42 +0100 Subject: [PATCH] react-panel: Clean up the JSONFormatter and make sure it updates both on mount and when props update --- .../JSONFormatter/JSONFormatter.tsx | 36 +++++++++++++------ 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/public/app/core/components/JSONFormatter/JSONFormatter.tsx b/public/app/core/components/JSONFormatter/JSONFormatter.tsx index 07b3fe45145..82560c07d33 100644 --- a/public/app/core/components/JSONFormatter/JSONFormatter.tsx +++ b/public/app/core/components/JSONFormatter/JSONFormatter.tsx @@ -1,38 +1,52 @@ -import React, { PureComponent } from 'react'; -import JSONFormatterJS from 'json-formatter-js'; +import React, { PureComponent, createRef } from 'react'; +import JSONFormatterJS, { JSONFormatterConfiguration } from 'json-formatter-js'; interface Props { className?: string; - json: any; - config?: any; + json: {}; + config?: JSONFormatterConfiguration; open?: number; } export class JSONFormatter extends PureComponent { - wrapperEl: any = React.createRef(); - jsonEl: HTMLElement; - formatter: any; + private wrapperRef = createRef(); + private formatter: any; static defaultProps = { open: 3, config: { animateOpen: true, + theme: 'dark', }, }; componentDidMount() { + this.renderJson(); + } + + componentDidUpdate() { + this.renderJson(); + } + + renderJson = () => { const { json, config, open } = this.props; this.formatter = new JSONFormatterJS(json, open, config); - this.jsonEl = this.wrapperEl.current.appendChild(this.formatter.render()); - } + const wrapperEl = this.wrapperRef.current; + const newJsonHtml = this.formatter.render(); + const hasChildren: boolean = wrapperEl.hasChildNodes(); + if (hasChildren) { + wrapperEl.replaceChild(newJsonHtml, wrapperEl.lastChild); + } else { + wrapperEl.appendChild(newJsonHtml); + } + }; componentWillUnmount() { this.formatter = null; - this.jsonEl = null; } render() { const { className } = this.props; - return
; + return
; } }