62

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?

1

2 Answers 2

121

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - simply replacing "ref" with "inputRef" did the trick for me.
6

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 .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.