Pressing the reset button will restore the table to its original

As a new React developer with experience mainly in hooks, I have been struggling to find a good example involving hooks. Currently, I am working on implementing an antd table with search functionality. My question is, when a user types something into the search bar and receives different results, how can I allow them to cancel that search by clicking a 'Reset' button?

Check out my code here

Answer №1

To assign a custom identifier to your input in the file TitleSearch.js:

<Search
      id='YOURCUSTOMID'
      placeholder="Enter Title"
      onSearch={onSearch}
      onChange={onChange}
      style={{ width: 200 }}
    />

Next, include an event in the file EventsSection.js

ResetInput = () => {
    const input = document.getElementById('YOURCUSTOMID');
    input.value = '';
    this.handleSearch('');
  }
  ....
 <button
  onClick={this.ResetInput}
 >Reset</button>

Remember to replace YOURCUSTOMID with the desired identifier

Answer №2

execute this script

Developed a novel function to reset the value and activate it using the reset button.

function:

resetValue = () =>{
        this.setState({
          eventsData: eventsData
        });
      }

And initiate from the button

<button onClick={this.resetValue}>Reset</button>

complete code::

import React, { Component } from "react";

import styles from "./style.module.css";
import { EventsTable } from "../EventsTable";
import { StatusFilter } from "../StatusFilter";
import { TitleSearch } from "../TitleSearch";

const eventsData = [
  {
    key: 1,
    title: "Bulletproof EP1",
    fileType: "Atmos",
    process: "match media",
    performedBy: "Denise Etridge",
    operationNote: "-",
    updatedAt: "26/09/2018 17:21",
    status: "complete"
  },
  {
    key: 2,
    title: "Dexter EP2",
    fileType: "Video",
    process: "Compliance",
    performedBy: "Dane Gill",
    operationNote: "passed",
    updatedAt: "21/09/2018 12:21",
    status: "inProgress"
  }
];

class EventsSection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      eventsData
    };
  }

  handleFilter = (key) => {
    const selected = parseInt(key);
    if (selected === 3) {
      return this.setState({
        eventsData
      });
    }

    const statusMap = {
      1: "complete",
      2: "inProgress"
    };

    const selectedStatus = statusMap[selected];

    const filteredEvents = eventsData.filter(
      ({ status }) => status === selectedStatus
    );
    this.setState({
      eventsData: filteredEvents
    });
  };

  handleSearch = (searchText) => {
    const filteredEvents = eventsData.filter(({ title }) => {
      title = title.toLowerCase();
      return title.includes(searchText);
    });

    this.setState({
      eventsData: filteredEvents
    });
  };

  handleChange = (e) => {
    const searchText = e.target.value;
    const filteredEvents = eventsData.filter(({ title }) => {
      title = title.toLowerCase();
      return title.includes(searchText);
    });

    this.setState({
      eventsData: filteredEvents
    });
  };

  resetValue = () =>{
    this.setState({
      eventsData: eventsData
    });
  }

  render() {
    return (
      <section className={styles.container}>
        <header className={styles.header}>
          <h1 className={styles.title}>Events</h1>
          <button onClick={this.resetValue}>Reset</button>
          <TitleSearch
            onSearch={this.handleSearch}
            onChange={this.handleChange}
            className={styles.action}
          />
        </header>
        <EventsTable eventsData={this.state.eventsData} />
      </section>
    );
  }
}

export { EventsSection };

Answer №3

My solution involved adding an onClick event to the button:

Here is the code snippet I used:

<button onClick={this.resetSearch}>Reset</button>

After clicking the button, I called the resetSearch function which set handleSearch to an empty string, effectively resetting the table:

  resetSearch = () =>{
  this.handleSearch('')
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

Creating dynamic pages using user input in Node and Express

Currently, I am facing a challenge in rendering text using node/express. Within my project setup, there is an HTML file containing a form. The file named search.ejs looks like this: $(document).ready(function(){ var userInput; $("#submit-button-i ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

"Addclass() function successfully executing in the console, yet encountering issues within the script execution

I dynamically created a div and attempted to add the class 'expanded' using jQuery, but it's not working. Interestingly, when I try the same code in the console, it works perfectly. The code looks like this: appending element name var men ...

What is the process for incorporating a CSS class into a preexisting Woocommerce/Wordpress widget?

Looking for a way to add additional classes to the Woocommerce Product Categories Widget without tampering with the original source code or creating a replacement widget? The widget_display_callback seems like the way to go, but the available documentation ...

Issues encountered while using React Drag and Drop functionality from Reactdnd

Currently, I am working on implementing drag and drop functionality for the pieces in my chess program using react-dnd module. For this purpose, I have integrated a chessboard component called chessboardjsx that also relies on reactdnd. However, upon runni ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

The AutoComplete component in React Material UI does not automatically assign the initialValue

I've encountered an issue with my form.js component. In this component, I have two states: update and create. Within the component, there's an AutoComplete component that works perfectly fine in the create state (data creation works as intended). ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...

Refreshable div element in a Code Igniter-powered web application

I am encountering difficulties with automatically refreshing my div using the CodeIgniter framework. My goal in the code snippet below is to have the particular div with id="lot_info" refresh every 1 second. The div is not refreshing, and an error message ...

Unexpected problem with redrawing HTML application in Android WebView

I created a basic nixie clock app using HTML and wrapped it in a WebView for use on Android. It consists of one HTML file, a JS file, a CSS file, and ten digit images. After a few hours, I noticed stripes appearing in the center of the screen where the an ...

Storing user input from a dynamic form into a database using Kendo UI

I've successfully populated dynamic input form fields. However, I'm unsure how to save the data into a database using a put/post API since I have only used a get API so far. HTML code <div id="renderform" class="form horizontal-for ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

VueJS Vuetify automatically centers default content

Vue cli version @ 5.0.6 | Vuetify version: [email protected] I have been utilizing Vue.js and Vuetify for some time now, and I can't shake the feeling that not all Vue.js/Vuetify components default to centered alignment. I recently initialized a ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...

Utilize Redux Form with Material-UI components to create a unique DatePicker form with enabled text input functionality

I am currently utilizing the DatePicker component within my Field from redux form. However, I am facing an issue where the date picker automatically opens every time I focus on the field. This prevents me from manually inputting or pasting a date using the ...

Utilizing Angular 2 for Integration of Google Calendar API

I recently attempted to integrate the Google Calendar API with Angular 2 in order to display upcoming events on a web application I am developing. Following the Google Calendar JavaScript quick-start tutorial, I successfully managed to set up the API, inse ...