luke
luke

Reputation: 49

React Redux Material-UI autocomplete

I am struggling to get the value out of the Material-ui Autocomplete when using redux-form. Has anyone solved this? I am using the exact example from the material-ui Autocomplete https://material-ui.com/components/autocomplete/ I am able to see the list options and it populates after clicking it twice, but I am unable to extract the real value, instead I am returning ({ title : 0 }) instead of the value.

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { Field, reduxForm } from "redux-form";
import { connect } from "react-redux";

class Form extends React.Component {
  onSubmit = formValues => {
    console.log(formValues);
  };

  renderTextField = ({
    label,
    input,
    meta: { touched, invalid, error },
    ...custom
  }) => (
    <Autocomplete
      label={label}
      options={this.props.movies}
      placeholder={label}
      getOptionLabel={option => option.title}
      onChange={input.onChange}
      {...input}
      {...custom}
      renderInput={params => (
        <TextField {...params} label={label} variant="outlined" fullWidth />
      )}
    />
  );

  render() {
    const { handleSubmit } = this.props;

    return (
      <div>
        <form onSubmit={handleSubmit(this.onSubmit)}>
          <Field
            name="propertySelector"
            component={this.renderTextField}
            label="Select Property"
            type="text"
          />
        </form>
      </div>
    );
  }
}
const mapStateToProps = state => {
  console.log(state);
  return {
    movies: [
      { title: "The Shawshank Redemption", year: 1994 },
      { title: "The Godfather", year: 1972 },
      { title: "Schindler's List", year: 1993 }
    ]
  };
};

Form = reduxForm({
  form: "auto_complete"
});

export default connect(mapStateToProps, null)(Form);

Upvotes: 3

Views: 2651

Answers (1)

Luke Hardy
Luke Hardy

Reputation: 43

Solved by passing in the (event, value) to the onChange props.

onChange={(event, value) => console.log(value)}

From the docs;

Callback fired when the value changes.

Signature:
function(event: object, value: T) => void
event: The event source of the callback.
value: null

Upvotes: 4

Related Questions