Home > OS >  how to get the value of a map returned button in react
how to get the value of a map returned button in react

Time:02-20

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".

CodePudding user response:

Data attributes are a good way.

For a button:

<button data-value={country} onClick={changeDisplay}>show</button>

Click handler:

const changeDisplay = (e) => {
   const { value } = e.target.dataset;
   console.log(value);
};

CodePudding user response:

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)} />
  • Related