React Rails Passing props to React Select

Viewed 619

I'm trying to pass props from my Rails database to a React Select component using React rails, but the text is appearing invisible within the select option.

View:

= react_component('SelectSearch', options: Course.all.as_json(only: [:title]))

React select component:

import React from 'react';
import Select from 'react-select';

class SelectSearch extends React.Component {
  constructor(props) {
      super(props)
    }

  state = {
    selectedOption: null,
  };

  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={this.props.options}
      />
    );
  }
}

export default SelectSearch;

When something in the select is clicked, it console logs, for example:

Option selected: {title: "English"}

But opening the select, its completely blank. There is obviously an option there that can be clicked, but nothing is displayed. Likewise for searching, no options are displayed.

I know this is because I'm passing the props incorrectly, or handling the data incorrectly, I don't want {title: "English"} I just want English but not sure how to filter this correctly.

2 Answers

See the react-select example:

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
]

const MyComponent = () => (
  <Select options={options} />
)

Your options contains unneeded 'title' attribute and not contains 'value' and 'label'. Fix it.

Took me a while to figure it out, but got this working:

= react_component('SelectSearch', data: Course.all.as_json(only: [:title]))
import React from 'react';
import Select from 'react-select';

class SelectSearch extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    selectedOption: null,
  };

  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={this.props.data}
        getOptionLabel={(option) => option.title}
        getOptionValue={(option) => option.title}
      />
    );
  }
}

export default SelectSearch;

React-select expects a value and a label and this seems to be the easiest way to pass it.

Related