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

A notification appears when the record is being inserted after clicking the button

Just venturing into the PHP and MYSQL realm, so please excuse any beginner questions. Before I submit data from a form to my SQL table, I'd like to display a confirmation POP UP message asking "Are you sure you want to insert this data?" ...

What is the best way to rewrite this code using the appropriate "react" methodology?

I'm currently working on updating the innerHTML of an element in react, but I realize that my current approach involves direct manipulation of the DOM which is not recommended. Can someone guide me on how to achieve this correctly? Should I be using u ...

What is the best way to show the probability of users' bets in percentage form based on their wagered amounts?

I am currently working on creating a Jackpot Roulette game that features a main pot. Each round sees users joining and placing bets that contribute to the main pot, with the winner taking home the entire amount. My goal is to provide each user with real-t ...

I am currently exploring next.js and working on creating a dedicated single post page within my project

I am currently working with Next.js and fetching some dummy data on the homepage. However, I am facing an issue when trying to create a separate page for each post obtained from the homepage. Although I have already coded it, I feel like there is room fo ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

Display a loading screen in ExpressJS until the data is fully loaded and ready for use

I am currently utilizing puppeteer to extract data from a job website, and so far everything is running smoothly. app.get('/', async (req, res) => { res.render('index', {text: 'This is the index page'}); }) Up ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

experiencing difficulties in retrieving the outcome from a sweetalert2 popup

function confirmation() { swal.fire({ title: "Are you absolutely certain?", text: "You are about to permanently delete important files", type: "warning", showCancelButton: true, show ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Issue with Material UI: Background elements inaccessible while MUI Dialog is active

Currently, I am in the process of styling a Chatbox using MUI and encountering an issue. When the Dialog is open, I am unable to interact with the background elements. Although I can click on the content within the Dialog, I cannot access the background Fo ...

Setting up a React App deployment with Nginx Reverse Proxy using Docker Compose

I have a Docker Compose project with multiple services (two APIs, database, and more). To expose the APIs over the network, I set up an Nginx container as a reverse proxy. In addition, I need to make a Web App developed in React accessible. This app gener ...

Encountering an issue where an error message indicates that a variable previously declared is now undefined

Currently, I am working on developing a small test application to enhance my coding skills. However, I have encountered a roadblock while attempting to display dummy information from a mongodb database that I have set up. I have tried various solutions bu ...

I keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

What steps should I take to display a Modal upon a successful Oauth2 redirect?

I am currently working on an older web application that utilizes the portal/portlet architecture. Within the application, I have a feature that loads in a modal when accessed. The modal includes navigation functionality that allows customers to navigate t ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...