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

Viewed 53860

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'/>
5 Answers

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()

Instead of using ref you should use inputRef

const MyComponent = () => {
  let input;

  return (
    <form
      onSubmit={e => {
        e.preventDefault();
        console.log(input.value);
      }}>
      <TextField
        hintText="Enter Name" 
        floatingLabelText="Client Name" 
        autoWidth={1}
        inputRef={node => {
          input = node;
        }}/>
    </form>
  )
};

Here is a short simple React Hook version of the answer

export default function MyCustomeField({
  initialValue= '', 
  placeholder= 'Enter your text...'
}) {
  const [value, setValue] = React.useState(initialValue)

  return (
    <div>
      <TextField
        placeholder={placeholder}
        value={value}
        onChange={e => setValue(e.target.value)}
      />
      <button onClick={() => setValue(initialValue)}>Reset Text</button>
    </div>
  );
}

I prefer this way to assign the state variables:

<TextField value={mobileNumber} 
     onChange={e => { this.setState({ mobileNumber: e.target.value }) }}
     className={classes.root}
     fullWidth={true}
     label={t('mobile number')} />
Related