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?
You may not use the ref attribute on function components because they don't have instances.
To get data from the React Material UI TextField component, we can get the input value from the onChange function. In the function, we can get the input value from the e. target. value property and set that as the value of a state.
To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With