Reputation: 888
someone can explain to me why this value in the renderInput function is undefined. I browse the code and everything looks good.
Here is error
Uncaught TypeError: Cannot read property 'renderError' of undefined
This is my component AddCatalog. When it calls console.log(this) in renderInput, this returns me undefinded
import React, {PropTypes} from "react";
import {Field, reduxForm} from "redux-form";
//
class AddCatalog extends React.Component {
constructor(props) {
super(props);
this.renderError = this.renderError.bind(this);
}
renderError({error, touched}) {
alert("asds");
if (touched && error) {
return <div className="red">{error}</div>;
}
}
renderInput({input, label, meta}) {
return (
<div className="form-group">
<label>{label}</label>
<input {...input} className="form-control" autoComplete="off" />
{this.renderError}
</div>
);
}
onSubmit(formValues) {
console.log(formValues);
}
render() {
return (
<form onSubmit={this.props.handleSubmit(this.onSubmit)}>
<div className="row paddingLR30 container-fluid">
<div className="col-12">
<h2>Dane placówki</h2>
</div>
<div className="col-3">
<Field label="Nazwa placówki*" name="name_kindergarten" component={this.renderInput} />
</div>
</div>
<button>Submit</button>
</form>
);
}
}
const validate = (formValues) => {
const errors = {};
if (!formValues.name_kindergarten) {
errors.name_kindergarten = "Musisz podać nazwę przedszkola";
}
return errors;
};
export default reduxForm({
form: "simple",
validate
})(AddCatalog);
Upvotes: 0
Views: 915
Reputation: 2927
Instead of calling this function like this.renderError()
, you gave a pointer like this.renderError
.
present code :
renderInput({input, label, meta}) {
return (
<div className="form-group">
<label>{label}</label>
<input {...input} className="form-control" autoComplete="off" />
{this.renderError}
</div>
);
}
correct code :
renderInput({input, label, meta}) {
return (
<div className="form-group">
<label>{label}</label>
<input {...input} className="form-control" autoComplete="off" />
{this.renderError()}
</div>
);
}
Upvotes: 2
Reputation: 781
Because renderInput is not called in the context of the component - you forgot to bind it to this
in the constructor the way you did with renderError
.
Upvotes: 1