import React, { useState, useEffect } from "react";
const CodeSnippetManager = () => {
const [snippets, setSnippets] = useState([]);
const [code, setCode] = useState("");
const [tag, setTag] = useState("");
const [search, setSearch] = useState("");
useEffect(() => {
const saved = localStorage.getItem("snippets");
if (saved) {
setSnippets(JSON.parse(saved));
}
}, []);
useEffect(() => {
localStorage.setItem("snippets", JSON.stringify(snippets));
}, [snippets]);
const addSnippet = () => {
if (code.trim() === "") {
alert("Code is required!");
return;
}
const newSnippet = { code, tag };
setSnippets([...snippets, newSnippet]);
setCode("");
setTag("");
};
const filteredSnippets = snippets.filter((snippet) =>
snippet.tag.toLowerCase().includes(search.toLowerCase())
);
return (
<div style={{ padding: "20px", maxWidth: "700px", margin: "auto" }}>
<h2>Code Snippet Manager</h2>
{/* Search Box */}
<input
type="text"
value={search}
placeholder="Search by tag"
onChange={(e) => setSearch(e.target.value)}
style={{ width: "100%", padding: "10px", marginBottom: "10px" }}
/>
{/* Code Input */}
<textarea
value={code}
placeholder="Paste your code here"
onChange={(e) => setCode(e.target.value)}
style={{ width: "100%", height: "100px", padding: "10px" }}
/>
{/* Tag input */}
<input
type="text"
value={tag}
placeholder="Tag (example: javascript)"
onChange={(e) => setTag(e.target.value)}
style={{ width: "100%", padding: "10px", marginTop: "10px" }}
/>
{/* Add Snippet Button */}
<button
onClick={addSnippet}
style={{
padding: "10px 20px",
marginTop: "10px",
backgroundColor: "#4CAF50",
color: "#fff",
border: "none",
cursor: "pointer",
}}
>
Add Snippet
</button>
{/* Display Snippet */}
<h3 style={{ marginTop: "30px" }}>Saved Snippet</h3>
{filteredSnippets.length > 0 ? (
filteredSnippets.map((snippet, index) => (
<div
key={index}
style={{
border: "1px solid #ccc",
padding: "10px",
marginBottom: "10px",
backgroundColor: "#f9f9f9",
}}
>
<pre style={{ whiteSpace: "pre-wrap" }}>{snippet.code}</pre>
<div style={{ fontSize: "12px", color: "gray" }}>
Tag: {snippet.tag}
</div>
</div>
))
) : (
<p style={{ color: "gray" }}>No Snippets found.</p>
)}
</div>
);
};
export default CodeSnippetManager;
👉 We're using this to manage the data for inputs and the snippet list (code, tag, search, snippets).