I have an array of objects in which each object has an onclick event. I map my array of objects to a component. I have a button in which I change a variable's value.
If I click my button, it changes the variable's value, but when I fire the onclick event on one of my components it does not use the variable's changed value. (I'm guessing that this is normal behaviour because the event was already binded to the component when it was created.)
Although, how can I use my updated variable value in my component's onClick event?
First I declare my variables
const [myVariable, setMyVariable] = useState("first value");
const [mymap, setmymap] = useState([
{
key: 1,
name: "one",
onClick: event => handleClick(event)
},
{
key: 2,
name: "two",
onClick: event => handleClick(event)
}
]);
setVariable is my onClick event of my first button that changes my variable's value
const setVariable = () => {
setMyVariable("second value");
};
handleClick is the onClick event of my components
const handleClick = () => {
console.log(myVariable);
};
Here I return my UI with my map of MyComponent
return (
<div>
<button onClick={setVariable}>Set variable</button>
<h1>{myVariable}</h1>
{mymap.map(element => (
<MyComponent key={element.key} onclickevent={element.onClick} />
))}
</div>
);