How can I change value of specific field on event.
Example not working (Cannot read property 'firstname' of undefined)
onclick1() {
this.props.fields.firstname.onChange("John")
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.submit.bind(this))}>
<Field
name="firstname"
component={TextField}
label="first name"
/>
<button onClick="this.onclick1()">Set name to John</button>
<button type="submit">
okay
</button>
</form>
This solution was proposed here but it is not working for me https://stackoverflow.com/a/36916183/160059
redux-form v7
I see some problems in your code:
<button onClick="this.onclick1()">
should be:
<button onClick={this.onclick1}>
and onclick1 should be somehow bound to the component. Besides, I usually use change
method to set a field value. So I would change your code to something like:
class ComplexForm extends React.PureComponent {
constructor(props) {
super(props);
this.onclick1 = this.onclick1.bind(this);
}
onclick1() {
this.props.change("firstname", "John");
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<Field name="firstname" component="input" label="first name" />
<button onClick={this.onclick1}>Set name to John</button>
</form>
);
}
}
Note that I only rewrote some relevant part of your code and I'm using a standard input
component cause I don't know how your TextField
looks like. Check online demo here