Reputation: 575
I am passing the option values into a series of Dropdown buttons, each of which is in a child component from a data array.
When an option is chosen in one of the buttons I am updating the state in the parent component with the result of onSelect. This is all working fine...
//parent component
sourceSelected = (event) => {
this.setState({
sourceSelected: event
});
...
<ButtonToolbar>
{MEDIUM.map((medium) =>
<Medium key={medium.medium_name} medium={medium} onSelectedValue{this.sourceSelected } />
)};
</ButtonToolbar>
//child component
<DropdownButton title={props.medium.medium_name} id="source-dropdown" onSelect={props.onSelectedValue}>
{props.medium.source.map((option, index) =>
<MenuItem key={index} eventKey={option}> {option} </MenuItem>)}
</DropdownButton>
However, I would also like to store in the state (mediumSelected=???) the name of the button from which the option was selected.
Is there anyway to get OnSelect to pass this back or should I do something else?
Upvotes: 1
Views: 8638
Reputation: 575
OK, I answered this using... https://reactjs.org/docs/handling-events.html passing arguments to event handlers.
The code is:
//parent component
sourceSelected = ( medium_name, event) => {
this.setState({
sourceSelected: event,
mediumSelected: medium_name
});
}
...
<div className='test'>
<ButtonToolbar>
{MEDIUM.map((medium) =>
<Medium key={medium.medium_name} medium={medium} onSelectedValue={this.sourceSelected.bind(this, medium.medium_name) } />
)};
</ButtonToolbar>
Upvotes: 1
Reputation: 21
You can take advantage of Javascript events and this
. Basically, pass the event to the function that will be using the button name, like this
<button name="btn" onClick={e => this.buttonName(e.target.name)}>
You will also need to bind this
in your constructor()
Example code:
constructor(props) {
super(props);
// Bind this so you can use it below
this.buttonName = this.buttonName.bind(this);
}
buttonName(e) {
console.log(e);
}
render() {
return (
<div>
// Pass the name of the button to the function
<button name="btn" onClick={e => this.buttonName(e.target.name)}>
Button
</button>
</div>
);
}
I also threw a quick example on https://codesandbox.io/s/lrwqr303vz. Don't mind the file names.
Upvotes: 0