I am having an issue using <TextField> with ref in my code. When I use it, the value passed to name and description is null:
handleClick() {
var name = this.refs.name.value;
var description = this.refs.description.value
}
render () {
return (
<React.Fragment>
<TextField 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>
);}
You can try using inputRef instead of ref for the TextField component. Here’s the updated code with the fix:
handleClick() {
var name = this.refs.name.value;
var description = this.refs.description.value
}
render () {
return (
<React.Fragment>
<TextField inputRef={(ref) => {this.refs.name = ref}} placeholder='Enter the name of the item' />
<input ref='description' placeholder='Enter a description' />
<Button onClick={this.handleClick.bind(this)}>Submit</Button>
</React.Fragment>
);}
By using inputRef instead of ref, you can pass a function that will set the ref to the desired value. In this case, the function sets this.refs.name to the value of the input element’s ref.