I'm learning ReactJS and Redux, and I cant figure out how to get access to my TextField instance while binding it's onChange callback to this
.
(I'm using material-ui for this example, but I would encounter quite the same problem without it)
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { setDataValue } from './actions/data';
import TextField from 'material-ui/lib/text-field';
import Paper from 'material-ui/lib/paper';
export class DataInput extends Component {
constructor(props){
super(props);
}
handleTextChange() {
this.props.setDataValue(document.getElementById('myField').value);
}
render(){
return (
<Paper style={{
width: '300px',
margin: '10px',
padding: '10px'
}}>
<TextField
id='myField'
defaultValue={this.props.data.value}
onChange={this.handleTextChange.bind(this)} />
</Paper>
);
}
}
export default connect(
(state) => ({data: state.data}),
{setDataValue}
)(DataInput);
I'm using a solution that I find ugly (not reusable => not very 'component-friendly') by setting an id
on my TextField, and accessing its value with document.getElementById('myField').value
How could I get rid of this id
, and accessing it with something like textFieldRef.value
inside my callback ?
I tried without .bind(this)
, which gives me access to my TextField instance through this
, but I can no longer access my this.props.setDataValue()
function since this
isn't binded to my class context.
Thank you !
Can we have two onChange event react? the expected should be onchange event has to be call both the functions. You can only assign a handler to onChange once. When you use multiple assignments like that, the second one will overwrite the first one.
Avoid using calls like document.getElementById
within a React component. React is already designed to optimise expensive DOM calls, so you're working against the framework by doing this. If you want to know how reference DOM nodes in React, read the docs here.
However, in this situation you don't actually need references. Placing a ref (or an ID) on TextField
isn't necessarily going to work. What you're referencing is a React element, not a DOM node.
Instead, make better use of the onChange
callback. The function passed to onChange
is called with an event
argument. You can use that argument to get the input value. (see React's event system.)
Your event handler should look like this:
handleTextChange(event) {
this.props.setDataValue(event.target.value);
}
And your TextField
should look like this:
<TextField
value={this.props.data.value}
onChange={event => this.handleTextChange(event)}
/>
Note: Use value NOT defaultValue.
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