简体   繁体   中英

How do I select value and options (label names) are invisible from react-select dropdown?

I am new to React. I'm using react-select and I've used the following code. The dropdown is displayed but I'm unable to see names and unable to view after selecting.

<Select
  variant="outlined"
  margin="normal"
  fullWidth
  value={this.state.selected}
  options={RewardAutomationsList}
  name="selected"
  onChange={this.handleChange}
  placeholder='None'
>
  {RewardAutomationsList.map((option) => (
    <option key={option.id} value ={option.name} label={option.name}>
      {option.name}
    </option>
  ))}
</Select>
handleChange = event => {
  this.setState({
    selected: event.name
  });
};

The RewardAutomationsList looks like this:

RewardAutomationsList:
  0:{name: "TEST 1 (INR 100)", id: "123"}
  1:{name: "test 2 (INR 250)", id: "456"}

Can someone help with this?

same npm package use like this block code.

 import React, { Component } from 'react'
    import Select from 'react-select'
    
    const options = [
      { value: 'chocolate', label: 'Chocolate' },
      { value: 'strawberry', label: 'Strawberry' },
      { value: 'vanilla', label: 'Vanilla' }
    ]
    
    const MyComponent = () => (
      <Select options={options} />
    )

react-select accepts an array of objects having label and value keys. Your option objects in RewardAutomationsList have id and name keys, so it can't be displayed. You need to change them.

Also, when you subscribe to change events with react-select 's onChange prop, the callback function you provide receives the selectedOption , not the event .

The following should work:

const RewardAutomationsList = [
  { label: "TEST 1 (INR 100)", value: "123" },
  { label: "test 2 (INR 250)", value: "456" },
];

class App extends React.Component {
  state = {
    selected: null,
  }

  handleChange = (selectedOption) => {
    this.setState({
      selected: selectedOption,
    });
  };

  render() {
    return (
      <React.Fragment>
        <Select
          fullWidth
          margin="normal"
          name="selected"
          onChange={this.handleChange}
          options={RewardAutomationsList}
          placeholder="None"
          value={this.state.selected}
          variant="outlined"
        />
        {/* It's not necessary and it's only here to show the current state */}
        <pre>{JSON.stringify(this.state, null, 2)}</pre>
      </React.Fragment>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM