kennechu
kennechu

Reputation: 1422

Clear Textfield material-ui ReactJS

I have two text fields and a button using Material-UI, what I want to achieve is to clear the contents of the text fields when I click the button but I don't know how to do it, I'm new to React-JS.

This is the code I have:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

export default class CreateLinksave extends React.Component {
    render() {
        return (
            <div clssName="container">
                <div>
                    <TextField floatingLabelText="Receipt Desc" />
                </div>
                <div>
                    <TextField floatingLabelText="Triggers Required" />
                </div>
                <RaisedButton label="Clear" />
            </div>
        );
    }
};

Can someone please help me on this?

Upvotes: 5

Views: 51907

Answers (4)

Goodsie
Goodsie

Reputation: 1

Just so there is a more up-to-date answer. I also find this is more on point for the question itself.

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

export default function FormClearExample() {

    const
        // create state const for form values
        [formName, setFormName] = useState(''),
        [formValue, setFormValue] = useState(''),

        handleSubmit = async (event) => {
            event.preventDefault();
            // do stuff here
            console.log(formName, formValue); // log form values
            // clear form values
            setFormName('');
            setFormValue('');
        };

    return (
        <Box sx={{ mt: 1 }} component="form" onSubmit={handleSubmit}>
            <Box sx={{ mt: 3 }}>
                <TextField
                    onChange={(e) => setFormName(e.target.value)} // update state const
                    margin="dense"
                    required
                    fullWidth
                    id="name"
                    label="Variable Name"
                    name="name"
                    value={formName} // use value from state const
                    autoFocus
                    size="small"
                />
                <TextField
                    onChange={(e) => setFormValue(e.target.value)} // update state const
                    margin="dense"
                    required
                    fullWidth
                    name="value"
                    value={formValue} // use value from state const
                    label="Value"
                    type="text"
                    id="description"
                    size="small"
                />
            </Box>
            <Typography sx={{ m: 1 }} component="h1" variant="h5">
                <Button
                    type="submit"
                >
                    Button Text
                </Button>
            </Typography>
        </Box>
    );
}

Upvotes: 0

Wimukthi
Wimukthi

Reputation: 41

If anyone has the same issue with the functional components in React, then you have to handle the value of the Textfield component with a state. Doesn't matter whether you use Formik library or not. Simple control the value property of the text field using a state variable.

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

const sampleTextControl = () => {
  const [value, setValue] = useState(''); //Initial value should be empty
  const handleSubmit = (e)=> {
    alert('The value: ' + value);
    setValue('');                        //To reset the textfield value
    e.preventDefault();
  }
  
  return ( 
    <form onSubmit={handleSubmit}>
      <Textfield id="standard-basic" value={value} onChange={(e)=>setValue(e.target.value)}/> 
      <Button variant="contained" type="submit" value="Submit">
        Submit
      </Button>
    </form >
  )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 2

Sumit
Sumit

Reputation: 310

If you don't want to manage state for every text field then you should use refs:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';

export default class CreateLinksave extends React.Component {
    constructor(props) {
      super(props);
      this.receiptRef = React.createRef('');
      this.triggersRef = React.createRef('');
    }

    handleClick = () => {
       this.receiptRef.current.value = null;
       this.triggersRef.current.value = null;
    }

    render() {
        return (
            <div clssName="container">
                <div>
                    <TextField floatingLabelText="Receipt Desc" />
                </div>
                <div>
                    <TextField floatingLabelText="Triggers Required" />
                </div>
                <RaisedButton label="Clear" onClick={this.handleClick}/>
            </div>
        );
    }
};

Upvotes: 0

Cristyan
Cristyan

Reputation: 670

the text should be handled by the state

therefore you must only edit the state of the component so that your changes are shown

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';


export default class CreateLinksave extends React.Component {
  constructor(props){
    super(props);
    // initial state
    this.state = this.getDefaultState();
  }

  getDefaultState = () => {
    return { text1: '', text2: '' };
  }

  clear = () => {
    // return the initial state
    this.setState(this.getDefaultState())
  }

 render() {
  return (
    <div className="container">
      <div>
          <TextField
            value={this.state.text1}
            onChange={(e)=>{this.setState({text1: e.target.value})}}
            floatingLabelText="Receipt Desc"
          />
      </div>
        <div>
          <TextField
            onChange={(e)=>{this.setState({text2: e.target.value})}}
            value={this.state.text2}
            floatingLabelText="Triggers Required"
          />
        </div>
        // use the clear function
        <RaisedButton label="Clear" onClick={this.clear}/>
    </div>
  );
 }
}

Upvotes: 11

Related Questions