2

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

2
  • How does your form look like? Will you share some code? Commented Dec 27, 2017 at 9:45
  • @Dario Updated example Commented Dec 27, 2017 at 11:25

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.