I've recently started learning react.js (loving it!) and ran into an interesting scenario with handling input values.
In the egghead tutorial they had you update an input using a ref
like so:
handleSubmit(){
var newNote = this.refs.note.value;
this.refs.note.value = '';
this.props.addNote(newNote);
}
<input type="text" ref="note" />
<button type="button" onClick={this.handleSubmit.bind(this)}>
Submit
</button>
Later, I was playing with the material ui library (also awesome) and ran into a problem where I couldn't update one of the material components (Probably because of this issue) using a ref
. After some time on Google I found that you could use a the state
, and just update it using an onChange
function, like so:
handleNoteChange(e){
this.setState({newNote: e.target.value});
}
<TextField
type="text"
value={this.state.newNote}
onChange={this.handleNoteChange.bind(this)} />
It seems like using a ref
would be easier, however, in my recent time learning react native, everything you do seems to be the second way, using an onChange
function and a state
variable.
So my question is, moving forward, would it be better to use one over the other? Maybe there are limitations which make using the state
better on native?
Instead of passing a ref attribute created by createRef() , you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.
The difference is that onChange sends an event, with the input value wrapped as part of the event, while onChangeText sends only the input value.
The onChange event in React detects when the value of an input element changes.
In React, avoid manipulating the DOM using references. You should never do anything like this:
this.refs.note.value = '';
It's fine to read from the DOM when necessary (usually in response to user input), but the only way information should pass from your application to the DOM is via your render()
method. Otherwise, the DOM becomes out of sync with your application. In React, your "source of truth" lives in memory, not in the DOM.
The second example you provide is the standard React way. The view - as defined by the render()
method - is ultimately derived from props
and state
. Changing the state triggers a change in view. So calling this.setState()
will force your component to re-render.
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