Last active
October 9, 2019 22:38
-
-
Save adavia/04c6084c1163585018950f1bb0b045b2 to your computer and use it in GitHub Desktop.
Dynamic field array react
This file contains hidden or 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 React, { useState } from 'react'; | |
| import { IoMdClose } from 'react-icons/io'; | |
| import { produce } from 'immer'; | |
| import { generate } from 'shortid' | |
| const StartupForm = () => { | |
| const [tags, setTags] = useState([ | |
| { | |
| id: '1', | |
| name: 'Physic' | |
| } | |
| ]); | |
| return ( | |
| <main className="py-6 px-4"> | |
| <form className="w-1/3 mx-auto"> | |
| <div className="px-3 pb-4"> | |
| <button className="bg-purple-500 hover:bg-purple-700 | |
| rounded-full text-white py-2 px-4" type="button" | |
| onClick={() => { | |
| setTags(currentTags => [...currentTags, { | |
| id: generate(), | |
| name: '' | |
| }]) | |
| }}> | |
| Add new tags | |
| </button> | |
| </div> | |
| {tags.map((tag, index) => { | |
| return ( | |
| <div className="w-full relative px-3 pb-2" key={tag.id}> | |
| <input className="appearance-none block w-full | |
| bg-gray-200 text-gray-700 border border-gray-200 rounded | |
| leading-tight focus:outline-none focus:bg-white | |
| focus:border-gray-500 py-3 px-4 mb-3" | |
| onChange={e => { | |
| const name = e.target.value; | |
| setTags(currentTags => | |
| produce(currentTags, v => { | |
| v[index].name = name | |
| }) | |
| ); | |
| }} | |
| value={tag.name} | |
| placeholder="Tag name" | |
| /> | |
| <button type="button" | |
| onClick={() => { | |
| setTags(currentTags => currentTags.filter(ct => ct.id !== tag.id)) | |
| }} | |
| className="absolute right-0 top-0 mt-4 mr-6"> | |
| <IoMdClose className="h-4 w-4 text-gray-600 | |
| hover:text-gray-800" /> | |
| </button> | |
| </div> | |
| ); | |
| })} | |
| </form> | |
| <div>{JSON.stringify(tags)}</div> | |
| </main> | |
| ); | |
| } | |
| export default StartupForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment