0

I need some help, I want to populate data into a Dropdown, I'm using material-ui but I don't know how to do it, I really new to react, I know that I can use props and then pass those to the dropdown but It's not that clear for me.

This is my code:

import React from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';



export default class CreateLinksave extends React.Component {

 constructor(props) {
   super(props);
   this.state = {value: 1
   };
   this.handleChange=this.handleChange.bind(this);
 }
 handleChange(event, index, value) {this.setState({value});}

render() {
 return (
    <div className="container">
     <div>
       <RaisedButton label="Copy an existing Global Multisave"/>
     </div>
      <div>
      <DropDownMenu value={this.state.value} onChange={this.handleChange}>
        <MenuItem value={1} primaryText="Never" />
        <MenuItem value={2} primaryText="Every Night" />
        <MenuItem value={3} primaryText="Weeknights" />
      </DropDownMenu>
      </div>
     </div>
  );
 }
}

as you can see, I have some options in my dropdown "hardcoded" but I want to make it dynamic, so if more options are added to props then this populate them automatically.

Can someone please help me with this.

Regards.

1 Answer 1

1

Assuming you can send those props as an array:

items = [
  { value: 1, primaryText: 'Never' },
  { value: 2, primaryText: 'Every Night' },
  { value: 3, primaryText: 'Weeknights' },
]

Simply map through them and you'll get the same result:

render() {
  return (
    <div>
      <DropDownMenu value={this.state.value} onChange={this.handleChange}>
        {this.props.items.map(item =>
          <MenuItem key={item.value} {...item} />
        )}
      </DropDownMenu>
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your time, just one more question, and don't know if its related to ES6 or something but Im getting an "SyntaxError: Unexpected token" on the array, the issue is on the "=" sign of the Items array.
Check whether you es6 configuration (mainly babel) supports arrow functions. If not, you can replace => to function(item) { return <MenuItem ... /> } and that also works.
Looks like the syntax is a bit off, the start should be curly: { this.props.item... NEVER MIND, i was able to edit post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.