dczii dczii - 1 month ago 22
React JSX Question

ReactJS - How can I set a value for textfield from material-ui?

I have a selectField and I want to set a value on it. Let say I type on it and when I click a button, the button will call a function that will reset the value of the textfield?

<TextField hintText="Enter Name" floatingLabelText="Client Name" autoWidth={1} ref='name'/>

Answer

You can do it in this way

export default class MyCustomeField extends React.Component {

      constructor(props) {
        super(props);

        this.state = {
          value: 'Enter text',
        };
      }

      handleChange = (event) => {
        this.setState({
          value: event.target.value,
        });
      };

     handleClick = () => {
        this.setState({
          value:'',
        });
      };

      render() {
        return (
          <div>
            <TextField
              value={this.state.value}
              onChange={this.handleChange}
            />
            <button onClick={this.handleClick}>Reset Text</button>
          </div>
        );
      }
    }