Search across the entire table in your React application with Global

Having trouble implementing global search with the new Material UI Next table component. I have a handleSearch method that takes an event as a parameter and uses regex to check if the event.target.value matches any data in the table. However, when I delete a search string, the columns do not update until I start typing again. How can I enable searching by number, not just by string, in this scenario?

const columns = [
    {
        dataKey: 'deviceType',
        label:'Device Type',
        numeric: false,
    }, {
        dataKey: 'deviceID',
        label:'Device ID',
        sortable: true,
        numeric: true,
        // cellRenderer: ({item, key}) =>
        //          <Button >Default</Button>,
    }, {
        ........
    }]
    
const data = [
    { key: 1, deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
    { key: 2, deviceType: 'Tag', deviceID: 2, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
    {.......},
]

class EnhancedTable extends Component {
    state = {
        selected: [],
        data,
        order: {
            direction: 'asc',
            by: 'deviceID',
        },
        search: '',
    }

    handleSearch = event => {
        debugger
        const {data} = this.state
        let filteredDatas = []
        filteredDatas = data.filter(e => {
            let matchedItems = Object.values(e)
            let returnedItems
            matchedItems.forEach(e => {
                const regex = new RegExp(event.target.value, 'gi')
                if (typeof e == 'string')
                    returnedItems = e.match(regex)
            })
            return returnedItems
        })
        this.setState({data: filteredDatas, search: event.target.value})
    }

    render = () => {

        const {data, search} = this.state

        return (
            <Paper>
                <Table
                    data={data}
                    search={search}
                    onSearch={this.handleSearch}
                />
            </Paper>)
    }
}
export default EnhancedTable 

Answer №1

 customSearchFunction = (text, search) => {
        debugger
        if (!text)
            return false
        if (!search)
            return true

        search = search.toLowerCase()
        text = text.toString().toLowerCase()

        let previousLetterPosition = -1

        return search.split('').every(s => {
            debugger
            previousLetterPosition = text.indexOf(s, previousLetterPosition + 1)

            return previousLetterPosition !== -1
        })
    }

    handleCustomSearch = search => {
        const {data} = this.state
        // debugger
        let filteredData = data.filter(x => Object.keys(x).some(key =>
            // debugger
            this.customSearchFunction(x[key], search)
        ))
    
        console.log(filteredData)
        
        this.setState({filteredData, search})
    }

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

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

Failing to hide a div on hover: Hoverintent's shortcomings

When I hover over the div with the unique identifier id="navbar", it doesn't seem to trigger any actions. I have included the following script in my document head: <script type="text/javascript" src="https://ajax.googleapi ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

Updating the state of an object nested within another object in React JS

So, I have a nested object within another object and I need to update the state of one or more properties in the inner object. This is my current state: const [products, setProducts] = useState({ name: '', type: '', price: '& ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...

What is the correct way to adjust the style.top attribute of an element using JavaScript?

In order to correct a JavaScript source code, I need to adjust the style.top property of a div element based on an integer parameter from a function called index. Here is the current implementation: div.style.top = (index * 22 + 2)+"px"; However, for lar ...

Can you explain what JSX is, its purpose, and the benefits of using it?

As I delve into the world of React, I can't escape the constant mention of JSX. Despite my efforts to grasp it by watching tutorials, the concept still eludes me. Even after consulting the documentation, my mind remains in a state of confusion. To m ...

Compatibility of image maps with browsers and the usage of imagemapster

Currently, I am utilizing ImageMapster to make adjustments to an image map while hovering. However, I am facing challenges with both the image map itself and the ImageMapster plugin. The issues I am encountering are: 1) Despite specifying a height and wid ...

Retrieve the tweets from the next Twitter user in the Array using blogger.js

I am working on a project that involves a javascript array of Twitter usernames. Using blogger.js, I successfully load the first username along with their last 5 tweets. Now, I am looking to create HTML buttons or links for "previous" and "next" in order ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

The POST function in jQuery often returns the [Object object] result

Looking to extract a string from a PHP file using jQuery's post method. function getString(string) { return $.ajax({ type: 'POST', url: 'scripts/getstring.php', data: { 'string': string } ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

What sets apart the $ and $() functions in jQuery?

After reviewing the jQuery API, I noticed that $() represents a collection of matched elements. However, I am curious about the significance of $. An example from the imagesLoaded library is provided below. if ( $ ) { $.fn.imagesLoaded = function( opt ...

How can I display JSX within an HTML tag attribute without receiving [object Object] as an output?

I'm facing an issue with React where instead of rendering HTML inside a data-tooltip attribute, it's displaying [object object]. class Hello extends React.Component { constructor(props) { super(props); this.hello = this.hello.bind(this ...

The Material UI 5 Autocomplete feature is not providing the expected filtered options

I am currently utilizing Material UI V5, Since the default filtering in Autocomplete does not provide the desired result array, I have implemented my own filterOptions function. const customFilter = (options, state) => { let result = options.filter(op ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...