Retrieve the initial value from the TextField

My website features multiple filters, including by date and duration, allowing users to easily find the information they need from a large dataset.

There is also a "reset all filters" button that clears all filters and displays the full list of products.

However, I encountered an issue with one filter that utilizes a TextField from mui. The problem is that when the user enters values to filter products, those values are reset instead of clearing the field itself when using the "reset all filters" button.

For example, if a user filters only by this field, then decides to reset all filters, the entered data remains in the field even though all other filters are cleared.

I need help solving this problem.

    const MAX_DURATION = 9999999 

export default function FilterDuration() {
  const [minDuration, setMinDuration] = useState(0);
  const [maxDuration, setMaxDuration] = useState(MAX_DURATION);

  useEffect(() => {
    updatedFilters.durationRange = { min: minDuration, max: maxDuration }
    setFilters(updatedFilters)
    if (maxDuration === 0) {
      setMaxDuration(MAX_DURATION)
    }
  }, [minDuration, maxDuration])

  return (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>

        <div style={{ width: "120px" }}>
          <TextField
           
            onInput={(e) => {
              
              const newValue = Number(e.target.value)
              if (newValue )
                setMinDuration(newValue)


            }} />
        </div>

      </div>

  );
}

Answer №1

To implement a minDuration functionality in your TextField, you need to include a value prop as shown below:

<TextField
  type='number'
  size="small"
  margin="dense"
  label="From"
  value={minDuration}
  onInput={(e) => {
    e.target.value = Math.max(0, parseInt(e.target.value)).toString().slice(0,7)
    const newValue = Number(e.target.value)
    if (newValue <= maxDuration && newValue >= 0 && newValue <= MAX_DURATION)
      setMinDuration(newValue)
  }} />

Answer №2

If you wish for the TextField to be controlled by your component's state, simply include a value attribute and assign it the current value of minDuration:

<TextField
    ...
    value={minDuration}
/>

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

Unfortunately, I am unable to transmit a cookie using the res.cookie method in Express

After setting up the route to send a JWT with a cookie, I'm unable to see it in my browser. Here's the code for the route: router.post('/signup', async (req, res) => { const { email, password } = req.body try { const ...

What guidelines should be followed for utilizing jQuery's Ajax convenience methods and effectively managing errors?

Imagine a scenario where I am trying to mimic Gmail's interface using jQuery Ajax to incorporate periodic auto-saving and sending functionalities. Error handling is crucial, especially in cases of network errors or other issues. Instead of just being ...

Slide your finger upwards to shut down the mobile navbar in bootstrap

Hey there, I'm currently developing a website using Bootstrap framework v3.3.4. I have a mobile navbar that opens when I click a toggle button, but I would like it to slide up to close the navigation instead. Here is an image showing the issue Do y ...

Store data retrieved in Next.js' getServerSideProps so that it can be accessed throughout the application without the need to continuously reload it each time the page is

I'm working on an index page where I fetch data using getServerSideProps. If I navigate to other pages using next/link or router.push(), is there a way for the fetched data to persist across all pages in my application? Or do I need to consider usin ...

The challenge of handling scopes in Angular-seed

I am currently facing a challenge with creating a pre-routeProvider post. The problem I'm encountering is that $http is coming up as undefined, even though I am passing it to the function as per my understanding. I have made sure to declare angular.js ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

What could be causing the callback function to not function correctly within the HOC component?

I am encountering an issue while passing the state (setActive) to the ButtonsOur component and then trying to pass it to the HOC through a callback. The error message "Uncaught TypeError: setActive is not a function" keeps popping up. Could you please help ...

Re-rendering a Highcharts chart for optimal display

I have implemented Highcharts to showcase a set of data through different types of charts - Area chart, Line chart, and Bar chart. By default, the page loads with the Area chart displayed. Upon clicking a button, I switch to displaying the Line chart and t ...

Switching the background image when hovering over a list element

Looking at the screenshot, it's clear that there is an unordered list with a background image set on the div. What I am trying to achieve is to have the background image change whenever I hover over a list item. Each list item should trigger a differe ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...

Improper menu alignment following a MenuItem hover event within Material-UI

When a MenuItem is hovered over, the position of the Menu container should remain unchanged. [x] The issue persists in the most recent release. However, downgrading MUI to v4.5.0 results in the expected behavior. Current Behavior ...

Steps for retrieving a Unicode string from PHP using AJAX

In order to retrieve Unicode strings from PHP for my project, I figured that using AJAX would be the most suitable method. $.ajax({ url: './php_page.php', data: 'action=get_sum_of_records&code='+code, ...

Unusual AngularJS error encountered while performing calculations on object properties

After running a specific calculation in my code, I encountered an unexpected issue. if (typeof $scope.memoryTable[name][category]['total'] !== 'undefined') { $scope.memoryTable[name][category]['total'] = $scope.memoryTabl ...

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

Using jQuery or JavaScript in an ASP.NET environment, you can make the parent list item of a dropdown link active

Welcome to my navigation menu <ul class="sidebar-menu" id="navigation-menu"> <li class="active"><a class="nav-link" href="/"><i class="fas fa-home"></i><span>Home Page</span></a></li> <li cl ...

How can you handle setting an array in JavaScript if a key/value pair does not exist when attempting to get it from a JSON object?

When dealing with a large JSON table stored in localStorage and a user-provided key, I need to access the associated value. However, if the key and/or value does not exist, my intention is to create them. But there's a roadblock... The JSON data prov ...

Extracting keys and values from a JSON string for analysis

My current code for the service now rest outbound call is functioning correctly. However, I am facing issues while trying to parse the JSON body in the second REST call and fetch values in the desired table format. try { var r = new sn_ws.RESTMessageV2 ...

What is the process for assigning a value to the body in a div element?

Within a div, there is a body element structured like this: <div id = "TextBox1"> <iframe id = "TextBox1_1"> #document <html> <head></head> <body></body> </html> </iframe> </div> I have attempte ...

What are the recommended callbacks for initiating ajax calls and managing files/chunks during dropzone chunk uploading?

I am currently working on implementing chunk uploading using dropzone js and php. My main concern is regarding the placement of ajax calls in this process. When dealing with single file uploads, specifying the URL parameter is sufficient. However, when ...