-
-
Save talatkuyuk/342c9c94d8965b27f99f2105f9d5cfe0 to your computer and use it in GitHub Desktop.
React JSON Viewer (Typescript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef } from "react"; | |
import styled from "styled-components"; | |
type Props = { | |
json: Object; | |
title?: string; | |
}; | |
const Container = styled.div` | |
width: 100%; | |
max-width: var(--max-width-dialog-box); | |
background: #fff; | |
padding: 1rem; | |
margin-top: 1rem; | |
border-radius: 5px; | |
box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.1); | |
display: flex; | |
flex-direction: column; | |
& .json-title-container { | |
width: 100%; | |
margin-bottom: 1rem; | |
padding: 0 1rem; | |
position: relative; | |
display: flex; | |
justify-content: space-between; | |
align-items: center; | |
border: 1px solid black; | |
} | |
& .json-title { | |
font-size: clamp(14px, 1.4rem, 18px); | |
font-weight: 600; | |
} | |
& #json-clear-icon { | |
color: red; | |
font-size: 125%; | |
} | |
& #json-clear-icon:hover { | |
cursor: pointer; | |
} | |
& .json-container { | |
width: 100%; | |
background-color: whitesmoke; | |
border: 1px solid gray; | |
padding: 1rem; | |
overflow-y: scroll; | |
font-size: clamp(12px, 1rem, 16px); | |
overflow: hidden; | |
} | |
pre { | |
white-space: pre-wrap; /* Since CSS 2.1 */ | |
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ | |
white-space: -pre-wrap; /* Opera 4-6 */ | |
white-space: -o-pre-wrap; /* Opera 7 */ | |
word-wrap: break-word; /* Internet Explorer 5.5+ */ | |
} | |
`; | |
const JsonViewer = ({ json, title = "Json Viewer" }: Props): JSX.Element => { | |
const ref = useRef<HTMLDivElement>(null); | |
return ( | |
<Container ref={ref}> | |
<div className="json-title-container"> | |
<span className="json-title">{title}</span> | |
<span | |
id="json-clear-icon" | |
className="material-icons" | |
onClick={(): void => { | |
ref.current?.remove(); | |
}} | |
> | |
clear | |
</span> | |
</div> | |
<div className="json-container"> | |
<pre> | |
<code>{JSON.stringify(json, null, 2)}</code> | |
</pre> | |
</div> | |
</Container> | |
); | |
}; | |
export default JsonViewer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use the component like below: