milan milan - 2 months ago 14
React JSX Question

Cannot read property 'length' of undefined[reactjs]

I am trying to count the remaining character using reactjs. I have defined the function which talks with the state and is passed down to the child component. In the child component i am getting an error of Uncaught TypeError: Cannot read property 'length' of undefined .

app.js

export default class App extends Component {
constructor(props){
super(props);
this.state = {max_char:32};
this.handleChange = this.handleChange.bind(this);
}

handleChange(charLength){
console.log('charLength');
this.setState({
max_char:32 - charLength.length
});
console.log(this.state.max_char);
}

render() {
return (
<div>
<Layout fixedHeader>
<Content>
<div className="page-content">
<DeviceEventList />
<DeviceDialog onChange={this.handleChange} />
</div>
<div className="empty-space">
</div>
</Content>
</Layout>
</div>
);
}
}


device-dialog.js

class DeviceDialog extends Component {
constructor(props) {
super(props);
console.log('this.props',this.props.onChange);
}

handleInputChange(event){
console.log(event.target.value);
let name = event.target.value;
this.props.onChange(name);
}

renderOwnADevice(){
console.log('open',this.props.active_device_event.open);
return(
<div className="device-action">
<Dialog open={this.props.active_device_event.open} onCancel={this.props.CancelDeviceEvent}>
<DialogContent>
<Textfield
onChange={()=> {this.handleInputChange(event)}}
pattern="-?[0-9]*(\.[0-9]+)?"
error="Input is not a number!"
label="Device Serial Number"
floatingLabel
/>
<span style={{ float:'right'}}>character</span>
</DialogContent>
</Dialog>
</div>
)
}


render() {
if ( !this.props.active_device_event){
return <h5 style={{ textAlign:'center' }}>Click icon based on your work</h5>;
}
let icon_name = this.props.active_device_event.icon_name;
if( icon_name == 'devices_other'){
return (<div>Device Other</div>);
}
if( icon_name == 'add_circle_outline'){
return (this.renderOwnADevice());
}
}
}

Answer

I would guess onChange={()=> {this.handleInputChange(event)}} should be onChange={(event) => {this.handleInputChange(event)}}. Now you're passing an event variable that's not defined.

As an aside: probably also better to bind the handler in the constructor like you did in app.js instead of having an anonymous function wrapper in your render.