PASSWORD RESET

Your destination for complete Tech news

How to empty an array in React JS?

2.12K 0
< 1 min read

To empty an array in ReactJS, you can simply reassign the array variable to a new empty array. Here’s how you can do it:

import React from 'react';

class EmptyArray extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      array: [1, 2, 3, 4, 5] // Your array here
    };
  }

  handleEmptyArray = () => {
    this.setState({ array: [] }); // Reassign the array to an empty array
  };

  render() {
    return (
      <div>
        <p>Array: {JSON.stringify(this.state.array)}</p>
        <button onClick={this.handleEmptyArray}>Empty Array</button>
      </div>
    );
  }
}

export default EmptyArray;

In this example, the handleEmptyArray method is called when the button is clicked. Inside this method, this.setState is used to update the state with an empty array, effectively emptying the array. The component’s render method then displays the current contents of the array and a button to empty it.

Remember that if you are not using state management like React’s setState, but rather a regular variable to hold the array, you can just assign an empty array to that variable to clear it.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.