For accessing React element or component, 'ref' is the best possible method? Do we have any other options for the same in ReactJS
<TextField
ref={(elem) => this.textField = elem}
value={value}
{...restProps}
/>
If you want to access the actual DOM node, then ref
is the only option. Generally ref
s are used to create uncontrolled components, where we let the DOM keep charge of the input's value, and get the value from our reference to the DOM node when we need it. You can't use value
as a prop on these components, but you can use defaultValue
to set their initial value:
class WithUncontrolledTextInput extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
console.log(`The input value is ${this.textField.value}`);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input ref={input => this.textField = input} defaultValue='hello' />
<input type='submit' value='Submit' />
</form>
);
}
}
The alternative approach is to use a controlled component, where the current value of the input is stored within the component's state, and updated whenever the input value is updated.
class WithControlledTextInput extends React.Component {
constructor() {
super();
this.state = {
textField: 'hello'
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInput = this.handleInput.bind(this);
}
handleSubmit(e) {
e.preventDefault();
console.log(`The input value is ${this.state.textField}`);
}
handleInput(e) {
this.setState({
textField: e.target.value
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input value={this.state.textField} onChange={this.handleInput} />
<input type='submit' value='Submit' />
</form>
);
}
}