Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'/> 
like image 958
dczii Avatar asked Mar 04 '16 08:03

dczii


People also ask

How do I change the default value in TextField material UI?

The MUI TextField can display a default value on render by using the defaultValue prop. This is useful if you don't need to externally get or set the TextField value, or if you are using a form. A form will automatically extract a TextField child components value on submit of the form.

How do you get the selected value from autocomplete material UI React?

To get the value in the React Material-UI autocomplete, we can get the selected values from the onChange callback. We add the Autocomplete from the @material-ui/lab module. And we set the options prop to the top5films array to add the options for the autocomplete.

How do you style a TextField in material UI?

To style a React Material UI text field, we can call the makeStyles function with a function that returns an object that specifies the styles. Then we can set the InputProps prop of the TextField to specify the styles of the input element in the text field.


2 Answers

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>         );       }     } 
like image 185
WitVault Avatar answered Sep 30 '22 07:09

WitVault


It's maintained that the right way is to have the component be controlled in a scenario like the accepted answer there, but you can also control the value in this gross and culturally unacceptable way.

<TextField ref='name'/>  this.refs.name.getInputNode().value = 'some value, hooray' 

and you can of course retrieve the value like so

this.refs.name.getValue() 
like image 37
James Avatar answered Sep 30 '22 05:09

James