1

I have:

<DropdownMenu text="Sort by" isOpen={this.state.activeDropdown === "Sort_by"} onSelect={this.setSort.bind(this)}
              onClick={this.showDropdown.bind(this, "Sort_by")}
              onMouseEnter={() => this.setState({mouseInDropdown: true})}
              onMouseLeave={() => this.setState({mouseInDropdown: false})}>
    <div onMouseEnter={() => this.setState({mouseInDropdown: true})}
         onMouseLeave={() => this.setState({mouseInDropdown: false})}>
        <li>Name</li>
        <li>Age</li>
        <li>Value</li>
    </div>
</DropdownMenu>

Which as you can see contains:

<li>Name</li>
<li>Age</li>
<li>Value</li>

In DropdownMenu.js I have:

render() {
    return <div className="dropdown__menu" onClick={this.props.onClick}>
        {this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
        <div className="dropdown__content"
             style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
            {
                this.props.children
            }
        </div>
    </div>
}

this.props.children renders out those options but how do I bind this.props.onSelect to each one in a way to get the value of the selected child?

Anas Abu Farraj
  • 1,540
  • 4
  • 23
  • 31
imperium2335
  • 23,402
  • 38
  • 111
  • 190
  • This is the answer you're probably looking for https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children – George Kemp Feb 28 '19 at 11:22

2 Answers2

0
render() {
        return <div className="dropdown__menu" onClick={this.props.onClick}>
            {this.props.text} {this.state.count > 0 ? <b>{this.state.count}</b> : ''}
            <div className="dropdown__content"
                 style={this.props.isOpen ? {'display': 'block'} : {'display': 'none'}}>
                {
                       React.Children.map(this.props.children, child => React.cloneElement(child, { onSelect: this.props.onSelect})
    );
                }
            </div>
        </div>
    }

For passing through the value of the list item to the onSelect callback I suggest creating a functional component

const ListItem = ({ onSelect, value }) => (
    <li onClick={() => onSelect(value)}>{value}</li>
)

And then you'd replace your li's with <ListItem value={"name"}> etc.

George Kemp
  • 541
  • 1
  • 7
  • 21
  • Fantastic, yeah sorry forgot to mention that I had fixed that typo. – George Kemp Feb 28 '19 at 14:48