Home > Back-end >  React: Selecting an element by id prints the wrong element
React: Selecting an element by id prints the wrong element

Time:11-28

handleRemoveItem(id) {
        const newResList = this.state.resolutions;

        function del(_i) { 
            delete newResList[_i];
        }

        let filtered = [];
        for(let i = 0; i < newResList.length; i  ) {
            if(newResList[i].k === id) {
                let el = document.getElementById(newResList[i].title   newResList[i].k);
                //el.classList.remove('animate__fadeInDown');
                //el.classList.add('animate__fadeOutLeft');
                console.log(el);
                del(i); // delete newResList[i]
            }
        }
        filtered = newResList.filter(function(el) {
            return el != null;
        });
        console.log(filtered);
        this.setState({resolutions: filtered});
    }

Hello! So, I am working on this list in react, when I add two elements to my list, and remove the first one added, it prints the other element that is left in the list. Is this normal? the 'id' is applied on creation of the list element and contains the title unique ID applied to the object.

Not to say that removing the list element doesn't work, but I've commented out the adding/removing of classes in this code because its being applied to the wrong element!

Any help is greatly appreciated


CodePudding user response:

when working with React there is a virtual DOM which handles all id's and function calls by the react logic.

If you want to, for example, select a element, there is no need to do it. Call a function directly from the element itself with onClick attribute and when other elements depend on this change, introduce state which you manipulate then.

More in the React Doc: https://reactjs.org/

  • Related