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

Creating dynamic selection options in an HTML select tag using PHP

When retrieving category and sub-category information from an API json file, the API returns category objects with a "parent" attribute. Main category objects have a parent attribute equal to 0, and sub-category objects have the parent attribute equal to t ...

"Spin an image using Javascript when it is shown on the

I've got a script that shows an image when we are attacked by a monster. The image is initially set to display="none", but switches to display="" when a monster appears. What I'm looking to do is make the image rotate 360° when it changes from ...

Is there a way to use node.js to retrieve a video in mp4 format?

My goal is to allow users to download a video from my AWS S3 bucket in MP4 format: app.get("/download_video", function(req,res) { filename = "s3.xxx.amazon.com/bucketname/folder/video_example.mp4"; // I'm unsure about the next steps }); Whil ...

Utilize CSS to style Hover effects

Can someone please assist me with this issue? I am having trouble getting the CSS to work for my hover effect. I suspect that there might be a problem with my syntax. Here is the HTML code: <div id="horizontalmenu"> <ul> <li><a h ...

Struggling to keep the page refreshed and stay on the same page in React, however, the state refuses to update as anticipated

My application is built using react, react-router-dom, and stitch for accessing MongoDB and handling authentication through Google. I am facing an issue where, after authenticating and accessing the ProtectedPage component, upon refreshing the page, the ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Querying an array using the Contentful API

Recently, I've been experimenting with the Contentful API (content delivery npm module) and have encountered a challenge that I'm not sure how to overcome. In my Contentful setup, I have a content type called tag which consists of one field, als ...

Utilizing Javascript within a PHP while loop to showcase map markers

Is there a way to display multiple database entries in a loop and show them as markers on a map like this: https://i.stack.imgur.com/SwaGP.png I am struggling with looping through JavaScript in PHP to display multiple markers. Is it possible to achieve t ...

Managing jquery values with cookies for loading, saving, and resetting

I recently implemented screen adjustments on my website using scrollbars. I utilized this example as a reference. Below is the code snippet... HTML CODE: <h1>Image Editor with CSS Filters and jQuery</h1> <!--Form for collecting image URL ...

Only import Bootstrap into a single component

I have a React website that uses a local SCSS file compiled to CSS. Now, I want to incorporate Bootstrap into just one component on the site. After following the instructions at , I managed to get Bootstrap working within my project. However, the issue ar ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

The user ID variable has not been declared

After successfully retrieving the username from a link, I am facing difficulty in getting the user id back. While displaying the username works perfectly fine, I encounter an issue with fetching the userId when trying to populate the thumbnail - it shows " ...

Increase the line spacing within paragraphs by eliminating the extra space at the top and bottom

Trying to adjust line height in a paragraph using CSS. Here is the HTML: <div> <p>Lorem ipsum dolor sit amet, oratio doctus his an. Nisl saperet delenit ad eos, his eros solet vituperata et, has tantas nemore consetetur ne. Nam cu au ...

The dropdown functionality in Bootstrap appears to be malfunctioning

Struggling to make the drop-down menu function properly in Bootstrap, but so far no success. Check out the code on this jsfiddle link. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-to ...

unable to properly display application.html.erb

I am encountering difficulties in rendering my application.html.erb template as I am receiving the following error message: ActionView::SyntaxErrorInTemplate within ApplicationController#home app/views/layouts/application.HTML.erb:10: syntax error, unexpec ...

I am having trouble inserting a table from a JSON object into an HTML file

getJSON('http://localhost:63322/logs', function(err, data) { if (err !== null) { alert('Something went wrong: ' + err); } else { //var myObj = JSON.parse(data); // document.getElementById("demo").innerHTML = myObj.ad_soy ...

Guide to Implementing StoreApi in Zustand LibraryLearn how to utilize Store

While reading the documentation for zustand, I came across a useful piece of information. In addition to the standard `set` and `get` parameters, there is an extra parameter called `api` in the StateCreator function. Check out the example below: import cr ...