Categories
React Answers

How to clear the Material UI text field Value in React?

Spread the love

Sometimes, we want to clear the Material UI text field Value in React.

In the article, we’ll look at how to clear the Material UI text field Value in React.

How to clear the Material UI text field Value in React?

To clear the Material UI text field Value in React, we can set the value property of the input to an empty string.

For instance, we write:

import React from "react";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";

export default function App() {
  const textInput = React.useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          textInput.current.value = "";
        }}
      >
        clear
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
}

to add a button and a text field.

We assigned the textInput ref to the TextField so we can its input value to an empty string when we click on the Button.

And we set the input value of the TextField to an empty string with textInput.current.value = "".

Conclusion

To clear the Material UI text field Value in React, we can set the value property of the input to an empty string.

2 replies on “How to clear the Material UI text field Value in React?”

Thanks alot! I’ve looked everywhere for this solution and you explained it simply and perfectly.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.