Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a React form with data if it exists

Tags:

reactjs

meteor

I'm trying to pre-populate a form with data from my mongoDB. I think I'm supposed to use componentDidUpdate() to setState the state of the form field, however, the page goes into an infinite loop. Very new to react so this might be an obvious question, I just haven't been able to find a solution.

Path: ContactDetailsComponent.js

export default class ContactDetails extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      'name.first': '',
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    var profileCandidate = this.props.profileCandidate;
    var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

    this.setState({
      'name.first': firstName,
    })

  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit} noValidate>

          <input
            name="name.first"
            type="text"
            value={this.state['name.first']}
            onChange={this.handleInputChange}
            className={this.state.errors['name.first'] ? "validate invalid" : "validate" }
          />

        </form>
      </div>

    )
  }
}

ContactDetails.propTypes = {
  profileCandidate: PropTypes.object,
};
like image 890
bp123 Avatar asked Dec 08 '25 08:12

bp123


1 Answers

You can slightly modify you following method

componentWillReceiveProps(nextProps) {
  var profileCandidate = nextProps.profileCandidate;
  var firstName = profileCandidate && profileCandidate.name && profileCandidate.name.first;

  this.setState({
    'name.first': firstName,
  })

}

This will set the updated props to state. Thanks

like image 181
Vinay Chaudhary Avatar answered Dec 10 '25 04:12

Vinay Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!