45

my original code was like this:

handleClick() {
  var name = this.refs.name.value;
  var description = this.refs.description.value
}
render () {
return (
  <React.Fragment>
    <input ref='name' placeholder='Enter the name of the item' />
    <input ref='description' placeholder='Enter a description' />
    <Button onClick={this.handleClick.bind(this)}>Submit</Button>
  </React.Fragment>
);}

name and description can get the inputs correctly. But when I use <TextField>:

<TextField ref='name' placeholder='Enter the name of the item' />

it shows that the value passed is null, it seems that ref does not work. Can anyone help me solve this problem?

GG-sof
  • 441
  • 1
  • 4
  • 4
  • Does this answer your question? [How to get password field value in react's material-ui](https://stackoverflow.com/questions/31446751/how-to-get-password-field-value-in-reacts-material-ui) – minus.273 Jan 08 '20 at 15:20

2 Answers2

96

String refs are deprecated and material-ui does not support using them. I recommend reading: https://reactjs.org/docs/refs-and-the-dom.html

Also to get a ref to the <input /> element you should use the inputRef prop. Read about it here.

If your React is up to date you should use createRef or the useRef hook. Below are some examples

// Using the useRef() hook. Only possible when you're using a function component.
const App = () => {
  const textRef = useRef();
  const showRefContent = () => {
    console.log(textRef.current.value);
  };
  return (
    <div className="App">
      <TextField inputRef={textRef} />
      <button onClick={showRefContent}>Click</button>
    </div>
  );
}
// Using createRef(). Use this when working in a React.Component
class App extends React.Component {
  constructor(props) {
    super(props);
    this.textRef = createRef();
  }

  showRefContent = () => {
    console.log(this.textRef.current.value);
  };

  render() {
    return (
      <div className="App">
        <TextField inputRef={this.textRef} />
        <button onClick={this.showRefContent}>Click</button>
      </div>
    );
  }
}

Or if your React isn't up to date you can store it in a local variable, but this isn't the preferred way.

class App extends React.Component {
  showRefContent = () => {
    console.log(this.textRef.value);
  };

  render() {
    return (
      <div className="App">
        <TextField inputRef={element => (this.textRef = element)} />
        <button onClick={this.showRefContent}>Click</button>
      </div>
    );
  }
}

Also, you might want to consider using state instead of having to create refs for all fields and then retrieving the values from the dom.

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
2

when you use "Text Field" you should use "inputRef" attribute instead of normal "ref" attribute . because mui textfield components is made of some nested normal html elements and with "ref" attribute you cannot access to any specific input value .

Mojito
  • 51
  • 3