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 73 74 |
import React, { useState, useRef } from "react"; import { Container, Form, Alert } from "react-bootstrap"; import CsvViewer from "react-csv-viewer"; import "bootstrap/dist/css/bootstrap.min.css"; const App = () => { const [fileContent, setFileContent] = useState(null); const [error, setError] = useState(""); const [fileUploaded, setFileUploaded] = useState(false); // Tracks if the file is uploaded const fileInputRef = useRef(null); // Ref to reset the file input field const handleFileUpload = (e) => { const file = e.target.files[0]; if (!file) { setError("No file selected."); return; } if (file.type !== "text/csv") { setError("Please upload a valid CSV file."); return; } setError(""); const reader = new FileReader(); reader.onload = (event) => { setFileContent(event.target.result); setFileUploaded(true); // Mark file as uploaded }; reader.onerror = () => { setError("Error reading the file."); }; reader.readAsText(file); }; return ( <Container className="my-4"> <h1 className="text-center">React CSV Viewer</h1> {/* File Upload */} {!fileUploaded && ( // Only show the file input if no file is uploaded <Form.Group controlId="csvFile" className="my-3"> <Form.Label>Upload a CSV File</Form.Label> <Form.Control type="file" accept=".csv" onChange={handleFileUpload} ref={fileInputRef} // Attach the ref to the file input /> </Form.Group> )} {error && <Alert variant="danger">{error}</Alert>} {/* CSV Viewer */} {fileContent && ( <div className="mt-4"> <CsvViewer data={fileContent} options={{ header: true, delimiter: ",", }} /> </div> )} </Container> ); }; export default App; |