1
votes

I have a component to build a dynamic drop down menu based on a URL which is REST API:

Combo component code:

export default class Combo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {data: [], value: 0}
    this.handleChange = this.handleChange.bind(this)
  }
  componentDidMount() {
    // Fetch content
  }
  handleChange(event, index, value) {
    this.setState({value: event.target.value});
  }
  render() {
    return (
      <MuiThemeProvider muiTheme={getMuiTheme()}>
        <DropDownMenu style={styles.customWidth} onChange={this.handleChange}>
          {this.state.data.map((row, i) => <ComboItem key={i} _id={row._id} label={row.name}/>)}
        </DropDownMenu>
      </MuiThemeProvider>
    )
  }
}

export class ComboItem extends React.Component {
  render() {
    return (
      <MenuItem style={styles.customWidth} value={this.props._id} key={this.props._id} primaryText={this.props.label}/>
    )
  }
}

in my index.js file I've added injectTapEventPlugin.

Finally it shows the output, but when I click on an item, it never change the value if drop down to the selected item (like normal selectbox).

Note: onChange method never called on any changes.

Demo:

enter image description here

1

1 Answers

1
votes

It looks like you need still need to pass this.state.value to the DrowDownMenu component as the value prop:

<DropDownMenu 
  style={styles.customWidth} 
  value={this.state.value} 
  onChange={this.handleChange}
>
  {this.state.data.map((row, i) => <ComboItem key={i} _id={row._id} label={row.name}/>)}
</DropDownMenu>

Edit:

Because you are wrapping your MenuItem component you actually need to pass the onTouchTap function to the MenuItems:

class ComboItem extends React.Component {
  render() {
    return (
      <MenuItem 
        value={this.props._id} 
        key={this.props._id} 
        primaryText={this.props.label} 
        onTouchTap={this.props.onTouchTap}
      />
    );
  }
}

This is usually done by the Menu component here.