How can I use ref in TextField

GG-sof picture GG-sof · Jan 8, 2020 · Viewed 11k times · Source

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?

Answer

Jap Mul picture Jap Mul · Jan 8, 2020

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 update to date you should use createRef of 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.