How can I change the value of an array from inside a map function using button onClick event. In the following example I defined and array name visitMyArray that has three objects and initially the value of visited key is set as false. Using map function I render the all the location inside a paragraph tag. There will be a button rendered for each paragraph. Is it possible to change the value of the visited from false to true if possible how can I do it.
import React from "react";
import {Button} from 'react-bootstrap';
class VisitComponent extends React.Component {
render(){
let visitmyArray = [
{
location:"Indiana",
visited:false
},
{
location:"Illinoi",
visited:false
},
{
location:"Ohio",
visited:false
}
]
return(
<div>
{visitmyArray.map((visitedArray, index) => {
<div key={index}>
<p>{visitedArray.location}</p>
<Button onClick={"Change the visited value from 'false' to 'true' for this object value"}>Continue</Button>
</div>
)})}
</div>
}
}
export default VisitComponent
You can set the visited property to true for each item on the map. Your onClick now would be
onClick={() => {visitedArray.visited = true}}
Using state, it might look something like this:
import React from "react";
import {Button} from 'react-bootstrap';
class VisitComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
visitmyArray: [
{
location:"Indiana",
visited:false
},
{
location:"Illinoi",
visited:false
},
{
location:"Ohio",
visited:false
}
]
};
this.toggleVisited = this.toggleVisited.bind(this);
}
toggleVisited(location) {
return ev => {
var locations = this.state.visitmyArray.slice(0);
var loc = locations.find(a => a.location === location);
loc.visited = !loc.visited;
this.setState({visitmyArray:locations})
}
}
render(){
let {visitmyArray} = this.state;
return(
<div>
{visitmyArray.map((visitedArray, index) => (
<div key={index}>
<p>{visitedArray.location}</p>
<button className={visitedArray.visited ? "visited" : ""} onClick={this.toggleVisited(visitedArray.location)}>Continue</button>
</div>
))}
</div>
)
}
}
export default VisitComponent
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