Add new element to DOM in React

I’m new to React, I try to create add a new element to DOM when onClick. So I play with the state. Like below:

const [number, setNumber] = useState(1);
const [item, setItem] = useState(() => [{id: number,task: `Task ${number}`}]);

const increaseItem = () => {
    setNumber(number + 1)
    console.log(number)
    setItem([...item, {id: number, task: `Task ${number}`}])
    console.log(item)
}

But I got an issue when I push the array in useState, the first element of the array copied twice. Here the result of the array:

4 //result of the number

/* Result of item */
0: {id: 1, task: "Task 1"}
1: {id: 1, task: "Task 1"}
2: {id: 2, task: "Task 2"}
3: {id: 3, task: "Task 3"}

Could you show me how the correct way to solve this. Thank you.

12 thoughts on “Add new element to DOM in React”

  1. const [number, setNumber] = useState(1);
    const [item, setItem] = useState([{
        id: number,
        task: `Task ${number}`
    }]);
    
    const increaseItem = () => {
        const newNumber = number + 1;
        setNumber(newNumber);
        console.log(number)
        setItem([...item, {
            id: newNumber,
            task: "Task " + newNumber
        }]);
        console.log(item)
    }
    
    increaseItem();
    
    Reply

Leave a Comment