5

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?

2
  • You're going to have to add some component methods and bind an event to your raised button Commented Nov 7, 2017 at 15:58
  • What version of Material-UI are you using? Commented Nov 7, 2017 at 16:04

4 Answers 4

11

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>
  );
 }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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>

1 Comment

Uncaught ReferenceError: require is not defined when trying to run code snippet
0

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>
        );
    }
};

Comments

0

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>
    );
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.