Vardan Hambardzumyan
Vardan Hambardzumyan

Reputation: 13

Add new user on button click in reactJS

I have following code

my code

I have a button "add", and when I am clicking "new user" was added in my array.

But it works only the first time when I am clicking second, third.... times nothing was happening. how many times I click so many times "new user" should be added into an array.

like this.

enter image description here

I am using functional components and useState hook.

Please help me resolve that problem

Upvotes: 0

Views: 1057

Answers (4)

ctrlaltdeleon
ctrlaltdeleon

Reputation: 406

In the Add.jsx what needs to change is:

  function add() {
    setAddNew(<NewUser />);
  }

into...

  function add() {
    setAddNew([...addNew, <NewUser />]);
  }

The previous function would keep resetting <NewUser/ > with itself, thus being only 1.

When adding the previous addNew state via ...addNew within an array [], thus being [...addNew, <NewUser />], this will take the previous state of addNew and add a <NewUser /> on top of that.

Upvotes: 0

Zahid Hasan
Zahid Hasan

Reputation: 622

Put the <NewUser /> inside of the setAddNew([...addNew])array. Check the following code:

function add() {
   setAddNew([...addNew, <NewUser />]);
}

Upvotes: 1

Yoandry Collazo
Yoandry Collazo

Reputation: 1212

Try this code in your Add.jsx

import React, { useState } from "react";

function Add() {
  const [addNew, setAddNew] = useState([]);
  function add() {
    // HERE is the change, you need to keep the previous values 
    setAddNew([...addNew, <NewUser />]);
  }

  return (
    <div>
      <button onClick={add}>Add </button>
      <div> {addNew} </div>
    </div>
  );
}
const NewUser = () => {
  return (
    <p>
      <div>New User </div>
    </p>
  );
};

export default Add;

addNew - is the state, in this case, an array.

setAddNew - is the function to handle the State, but you need to handle the logic

Upvotes: 0

Ali Asgher Badshah
Ali Asgher Badshah

Reputation: 851

This is happening because you are resetting the value of array for pushing new value to it you have to use

setAddNew((old) => [...old, <NewUser />]);

this will copy your old array and will also insert the new element to it

Upvotes: 0

Related Questions