Home > Mobile >  How to remove the all elements from Array in React
How to remove the all elements from Array in React

Time:10-20

I have the array with ids

const [selected, setSelected] = React.useState<readonly string[]>([]);
var selectedId = props.selectedId;  

When clicking on the clean button I have added a useState() which check the given selectedId has a value or not If selectedId has a value then add a value in array, if not then remove all the elements from the array

useEffect(() => {
        if (selectedId != undefined) {  
            // Add selectedId in selectedIdsList
            setSelected(selectedId)
        } else {
            // remove all elements from setSelected
        }
    }, [selectedId]);

How to delete all elements from array

CodePudding user response:

To delete all elements inside array or empty an array we can do something like this selectedIdsList = [] but since you are using state you can set it something like this

 setSelected([]);

CodePudding user response:

You can reassign the array to an empty array selectedIdsList = []

CodePudding user response:

you should write setSelected([])

  • Related