Home > Blockchain >  i have two components{addressone},{addresstwo} and want to add and delete {addresstwo} on button cli
i have two components{addressone},{addresstwo} and want to add and delete {addresstwo} on button cli

Time:06-25

address two component

 `<AddressTwo/>`

i had applied toggle logic but i am trying to add and delete component

  <Button
    onClick={()=>setIsToggled(!isToggled)}> </Button>

    {isToggled && <AddressTwo/>}

add when this is clicked

   `<Button > </Button>`

remove component when this button is clicked

  ` <Button>-</Button>`

CodePudding user response:

Change your way to do,

think that the address is one component that receives 1 object

{ id: Number, street: String, number: String, postCode: String }

and the number of addresses is an array of object

[ {...}, {...}]

in react it's maybe easier to manage this way

const [addresses, setAdresses] = useState([])

const addOne = () => setAddresses([...addresses, { id: null, street: "", number: "", postCode: "" }]

{...}

return(
  <>
    <h1>hello from profile</h1>
    <button onclick={()=>addOne()}/> </button>
    {addresses.map((address, i)=>(
       <AddressComponent address={address} />
    )}
  </>
)

the code is not perfect but you got the IDEA

then from there, you can play with the array as you want... (pop, push, limit, find, etc...)

courage...

  • Related