App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import React, { useState } from "react"; import { Container, Form, Alert } from "react-bootstrap"; import ReactJson from "react-json-view"; import "bootstrap/dist/css/bootstrap.min.css"; const App = () => { const [jsonContent, setJsonContent] = useState(null); const [error, setError] = useState(""); const handleFileUpload = (e) => { const file = e.target.files[0]; if (!file) { setError("No file selected."); return; } if (!file.name.endsWith(".json")) { setError("Please upload a valid JSON file."); return; } setError(""); const reader = new FileReader(); reader.onload = (event) => { try { const parsedJson = JSON.parse(event.target.result); setJsonContent(parsedJson); } catch (err) { setError("Invalid JSON file."); } }; reader.onerror = () => { setError("Error reading the file."); }; reader.readAsText(file); }; return ( <Container className="my-4"> <h1 className="text-center">React JSON Viewer</h1> {/* File Upload */} <Form.Group controlId="jsonFile" className="my-3"> <Form.Label>Upload a JSON File</Form.Label> <Form.Control type="file" accept=".json" onChange={handleFileUpload} /> </Form.Group> {error && <Alert variant="danger">{error}</Alert>} {/* JSON Viewer */} {jsonContent && ( <div className="mt-4"> <h5>JSON Content:</h5> <ReactJson src={jsonContent} theme="monokai" iconStyle="circle" collapsed={false} enableClipboard={true} displayDataTypes={true} displayObjectSize={true} /> </div> )} </Container> ); }; export default App; |