I have several dynamically generated material UI buttons, and when user clicks any of them I would like to know which was clicked (let's say obtain the value of name
attribute which I assigned below).
How can this be solved? Basically I want to retrieve some attribute of the button which was clicked.
Here is some code
{
that.state.items.map(function (item) {
return (
<div key={item.id}>
<FlatButton
label={item.regionName}
name={item.id}
primary={true}
onClick={that.handleRegionClick}
></FlatButton>
</div>
);
});
}
handleRegionClick(e);
{
console.log(e.target.name); // This prints undefined
// If I could get here the _item.id_ which I assigned to _name_ I would be fine.
}
PS. I also have this in constructor
this.handleRegionClick = this.handleRegionClick.bind(this);
To get the value of an input on button click in React: Create a state variable to store the value of the input field. Set an onChange event handler on the input to update the state variable when the input field value changes. Set an onClick event handler on a button element.
To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button in the browser. Similarly, you can call the navigate function with -2 to go 2 pages back.
How will you detect browser back button event in react? It depends on the type of Router you use in React. If you use BrowserRouter from react-router (not available in react-router v4 though), as mentioned above, you can use the action 'POP' to intercept the browser back button.
Your question looks weird to me. You can simply do it.
<FlatButton label={item.regionName} name={item.id} primary={true} onClick={that.handleRegionClick.bind(this, item.id)}></FlatButton>
handleRegionClick(itemId){
console.log(itemId)
}
You can do one thing, instead of assigning the id to name, bind
that id with onClick
handler function. Whenever any of the button will be clicked, it will pass that id to handler function.
Like this:
let a = [{ id: 1 }, { id: 2 }, { id: 3 }];
a.map(item => {
return <FlatButton
label={item.regionName}
primary={true}
onClick={() => this.handleRegionClick(item.id)} />
})
handleRegionClick
function:
handleRegionClick(id){
console.log(id);
}
Note: binding of handleRegionClick
is not required here because here, we are using arrow function
with onClick and calling handleRegionClick
normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With