StochasticNerd StochasticNerd - 7 days ago 5
React JSX Question

Mapping over a dictionary to display dropdown values in Javascript

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.

Answer

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>

Comments