Skip to content

Instantly share code, notes, and snippets.

@MForMarlon
Created June 19, 2020 07:03
Show Gist options
  • Save MForMarlon/fbc3eaef0b4155836e72dc7666ffaa98 to your computer and use it in GitHub Desktop.
Save MForMarlon/fbc3eaef0b4155836e72dc7666ffaa98 to your computer and use it in GitHub Desktop.
Simple React Tags generator
import React, {useState, useEffect} from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Tags tags={['abc', '123']} />
</div>
);
}
function Tags(props) {
const [tags, setTags] = useState([]);
const [newTag, setNewTag] = useState('');
useEffect(() => {
if (props && props.tags && props.tags.length) {
setTags(props.tags);
}
}, [props])
const addTag = ev => {
ev.preventDefault();
if (newTag.length) {
setTags([...tags, newTag]);
setNewTag('');
}
}
const removeTag = idx => {
const tagsCopy = [...tags];
tagsCopy.splice(idx, 1);
setTags(tagsCopy);
}
return (
<div>
{tags.map((tag, index) => (
<div key={index} className="tag">
{tag}
<span
className="remove-tag"
onClick={() => removeTag(index)}
>&times;</span>
</div>
))}
<form className="new-tag-form" onSubmit={addTag}>
<input
type="text"
onChange={ev => setNewTag(ev.target.value)}
value={newTag} />
</form>
</div>
)
}
.App {
font-family: sans-serif;
text-align: center;
}
.tag {
display: inline-block;
margin-right: 5px;
background-color: #ccc;
padding: 5px;
}
.remove-tag {
margin-left: 5px;
cursor: pointer;
}
.remove-tag:hover {
font-weight: bold;
}
.new-tag-form {
display: inline-block;
}
.new-tag-form > input {
width: 150px;
padding: 5px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment