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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

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. Required fields are marked *