'how to get the value of a map returned button in react
return (
<div>
{
countries.map((country)=>
<div key={country.ccn3}>
{country.name.common}<button className="button" value={country} onClick={ChangeDisplay}>show</button>
</div>
)
}
</div>
);
}
as the code show: how do you get the value of "button", in my case, value should be "country" obj, which can be rendered with onClick function "ChangeDisplay".
Solution 1:[1]
You can simply get the value from e.target.value like how you do with form fields. Value needs to be a string.
const App = () => {
const onClick = (e) => alert(e.target.value)
return (<button onClick={onClick} value="my button value">MyButton</button>)
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you want to pass an Object. Then you can do without event by simply passing the object to the function.
<button onClick={()=> ChangeDisplay(country)} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Someone Special |
