1

I'm really new to Javascript and the whole idea of functional programming. Thus the question. So I have a dropdown menu as a React Component,

class Dropdown extends React.Component{

  render(){
    return(
        <SplitButton title="Dropdown">
          <MenuItem href="#books">Books</MenuItem>
          <MenuItem href="#podcasts">Podcasts</MenuItem>
          <MenuItem href="#">Tech I Like</MenuItem>
          <MenuItem href="#">About me</MenuItem>
          <MenuItem href="#addBlog">Add a Blog</MenuItem>
        </SplitButton>
    );
}

I want to replace the hardcoded values with values from a hashMap and get something like this.

render(){
<SplitButton title={chosenKey}>
   {dict.map(this.displayOptions)}
</SplitButton>
}

This is the displayOptions function,

displayOptions(){
    return(
      <MenuItem href="#" onClick={this.onDropDownClick}>{}</MenuItem>
    );
  }

Which I'm not able to get right, here's what I'm trying to do. Display the Key of the hashMap, but on click capture the value. This is my hashMap,

const dict = {
  "A" : "123",
  "B" : "234",
  "C": "345",
  "D": "456",
  "E": "567",
  "F": "678",
  "G" : "789"

};

Would really appreciate some Black Friday help with this.

1
  • 1
    Your "hashmap" isn't a hash map, it's an object. (This is more important than it used to be, as JavaScript now has a Map class.) Commented Nov 25, 2016 at 18:38

1 Answer 1

3

Here's a very simple example that uses Object.keys to map over your dict object:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      dict: {
        "A" : "123",
        "B" : "234",
        "C": "345",
        "D": "456",
        "E": "567",
        "F": "678",
        "G" : "789"
      }
    };
  }
  
  onClick(value) {
    console.log(value);  
  }

  render() {
    const dict = this.state.dict;
    return (
      <ul>
        {Object.keys(dict).map(key => (
         <li>
           <a
             href={`#${dict[key]}`}
             onClick={this.onClick.bind(this, dict[key])}
             key={key}>
             {key}
           </a>
         </li>))}
      </ul>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

This does solve the first part of the problem, could you help with capturing the value inside the onDropDownClick
Not sure if I understand what your goal is. Updated my answer. Does that help?
Yup it does. Thanks.

Your Answer

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