How to add second function onClick, when was map and render i need to add class change on all buttons to make them dynamic look
function ButtonsDes({button, filter}) {
return (
<div className="planet__btn">
{
button.map((e, i)=>{
return <button type="button" onClick={() =>filter(e)} key={i}>{e}</button>
})
}
</div>
);
}
export default ButtonsDes;```
CodePudding user response:
What I would recommend if you want the function to be dynamic, is to pass dynamic value, Also you are doing in the right way, just you need to understand, let me give you an example.
function ButtonsDes({button, filter}) {
// button value is like button= ['green', 'blue', 'yellow']
return (
<div className="planet__btn">
{
button.map((color, i)=>{
return <button type="button" onClick={() =>filter(color)} key={i}>{color}</button>
})
}
</div>
);
}
export default ButtonsDes;
Here when a html button is generated the filter function will get different color, on your filter color you can check for filter value and have different logic based on that, possible implementation for filter function
function filter(color) {
if (color === 'red') {
// your custom logic goes here
} else if (color === 'green') {
// your custom logic when color is green.
}
}
CodePudding user response:
If you have to apply two function on a button click at the same time, then you can do like this
<button type="button" key={i} onClick={() => { function1(); function2();}}>{e}</button>
or you can create wrapper function, something like this
wrapperFunction = () => {
//do something
function1();
//do something
function2();
}
These functions can be defined as a method on the parent class and then called from the wrapper function.
onClick={wrapperFunction}