Published on

How To use react-select within redux-form

Authors

In this tutorial, we'll see how to use custom components like react-select within redux-form.

So the first thing we need to do is to create a custom component. In our case, we are going to create a component for Select which will fetch data from an API endpoint.

import React, { Component, PropTypes } from 'react';
import axios from 'axios';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

class SelectInputAsync extends Component {
  constructor(props) {
    super(props);
    this.url = this.props.url;
  }
  getOptions() {
    return axios.get(this.url).then(response => {
      return { options: response.data };
    });
  }
  onChange(event) {
    // console.log(event)

    if (this.props.input.onChange && event != null) {
      // To be aligned with how redux-form publishes its CHANGE action payload. The event received is an object with 2 keys: "value" and "label"
      this.props.input.onChange(event.value);
    } else {
      // Clear the input field
      this.props.input.onChange(null);
    }
  }

  render() {
    return (
      <Select.Async
        {...this.props}
        value={this.props.input.value || ''}
        onBlur={() => this.props.input.onBlur(this.props.input.value)}
        onChange={this.onChange.bind(this)}
        loadOptions={this.getOptions.bind(this)}
      />
    );
  }
}

export default SelectInputAsync;

Let's create a simple signup form with a custom component which we just created.

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import SelectInputAsync from './SelectInputAsync';

export class SignUpForm extends Component {
  constructor(props) {
    super(props);
  }
  onFormSubmit(formData) {
    // Dispatch an action
    console.log(formData);
  }
  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={onFormSubmit}>
        <Field
          name="country"
          component={SelectInputAsync}
          url="https://api.myjson.com/bins/4gzai"
        />
      </form>
    );
  }
}
export default reduxForm({
  form: 'signup',
})(SignUpForm);