Search code examples
reactjsreduxstateredux-form

Passing a function from an object to the component to edit the state


I have a FIELDS object containing settings for many fields (also objects) that will be used to build the input fields in my page with the function renderField. Some of these fields need a function to edit the state of the component. I need this to be able to do some sort of autocompletion while the user is filling the form.

The code looks like this.

import React from 'react';
import {Field,reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import _ from 'lodash';

// objects that will be used to create the form
const FIELDS = {
  first_name: {
    type: 'text',
    label: 'First name',
    onChange: function(e){
      this.setstate({first_name:e.target.value})
  },
  last_name: {
    type: 'text',
    label: 'last name',
    onChange: function(e){
      this.setstate({last_name:e.target.value})
  },
  ...
  }
  
  class App extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        first_name : '',
        last_name : '',
        birth : '',
        sex:''
      };
    }
    
    renderField(field) {
      const fieldConfig = FIELDS[field.input.name];
      const {meta: {touched, error}} = field;

      return (
        <div className={`form-group ${touched && error ? 'has-danger' :''}`}>
          <br />
          <label>{fieldConfig.label}</label>
          <input
            {...fieldConfig}
            {...field.input}
          />
          <div className='text-help'>{touched ? error : ""}</div>
          <br />
        </div>
      );
    }

    onSubmit(){
        ...
    }

    render() {
      const {handleSubmit} = this.props;
      return (
        <div>
         <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
            { _.keys(FIELDS).map( key => {
              return <Field name={key} key={key} component={this.renderField} />;
              })
            }

          <button type='submit'>Submit</button>
        </form>
      </div>
    )
  }
}

export default reduxForm({
  // validate,
  form: 'Form example'
})(
  connect(null)(App)
);

I know that I can't call this.setState() this way, but I have no idea how I could bind the function inside the object inside the component. I did a lot of research and can't seem to find a solution. I don't know if it's because I'm not following good practices or not.

Thanks in advance


Solution

  • I found a solution. Instead of doing something complicated I just moved the function from the object directly in the render function in the component, making the connection to the state possible.