Home > Mobile >  In reactjs dropdown, how to pass specific value and not whole array?
In reactjs dropdown, how to pass specific value and not whole array?

Time:11-03

I'm getting correct values in dropdown but after that when I'm calling onchange, whole array is getting passed as argument. so e has the whole array and not just the value selected this is the code:

const { accountIDs } = this.state;
    let accountIDlist = accountIDs.length > 0
      && accountIDs.map((item, i) => {
        return (
          <option key={i} value={item}>{item}</option>
        )
      }, this);




<Select
            style={{ width: "100%" }}

            defaultValue="188619942792"
            autosize={true}
            
            onChange={e => {
              debugger;
              console.log(e);
              this.reset()
              this.setAccountID(e)
            }}
             >
             
            
            <select value={accountIDlist}>{accountIDlist}</select>

          </Select >

CodePudding user response:

You main component should be managing the state, so load in the ids, and initially set selected to nothing. Then pass in the ids and selected state to your Select component. That will iterate over the ids to create the options, and if the id of an option matches that of the selection set the selected property.

const { Component } = React;

class Select extends Component {
  render() {
    const { ids, selected, handleChange } = this.props;
    return (
      <select onChange={handleChange}>
        <option selected>Choose</option>
        {ids.map(id => {
          return (
            <option
              value={id}
              selected={selected === id}
            >{id}
            </option>
          );
        })}
      </select>
    );
  }
}

class Example extends Component {

  constructor(props) {
    super();
    this.state = { ids: props.ids, selected: '' };
  }

  handleChange = (e) => {
    this.setState({ selected:  e.target.value });
  }

  render() {
    const { ids, selected } = this.state;
    return (
      <Select
        ids={ids}
        selected={selected}
        handleChange={this.handleChange}
      />
    );
  }

};

const ids = [1, 2, 3, 4, 5];

ReactDOM.render(
  <Example ids={ids} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

<select
  name="account_id"
  onChange={handleChange}
>
  {props.accountIDList.map((accountId) => <option value={accountId}>{accountId}</option>)}
</select>

You can set the default when you set up state like so... const [accountId, setAccountId] = React.useState(account_id: 188619942792);

  • Related