How to add clear button on mui textfield in react js?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To add clear button on mui textfield, set this setValue onClick event of the mui textfield. It will clear the mui textfield.

Today, I am going to show you, how to add clear button on mui textfield in react js.

Installation

Install the following packages to use mui textfield in react js.

npm

npm install @mui/material @emotion/react @emotion/styled

yarn

yarn add @mui/material @emotion/react @emotion/styled

MUI material textfield clear button example.

The below code is an example of making clear button input using mui textfield.

App.js

import React, { useState } from "react";
import Box from '@mui/material/Box';
import InputAdornment from '@mui/material/InputAdornment';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';

export default function ClearTextField() {
  const [value, setValue] = useState("Original Val");
  return (
    <Box m={1}>
      <TextField
        onChange={(newValue) => {
          setValue(newValue.target.value);
        }}
        variant="outlined"
        defaultValue={value}
        value={value}
        label="TextField"
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <Button
                variant="outlined"
                onClick={() => {
                  setValue('');
                }}
              >
                Clear button
              </Button>
            </InputAdornment>
          ),
        }}
      />
    </Box>
  );
}

In the above code example, I have used the @mui/material TextField component and added clear button of MUI Textfield.

Check the output of the above code example.

React, Mui Textfield Clear Button

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Related Posts