I am new to React and wanted to write a fun project to get a hang of the language. I wanted to write a bubble blowing app, like so I wrote the following JSFiddle:
I am rendering an array of bubble objects stored in the following manner:
history =
[ { //first element is empty placeholder
diameter: 0,
x: 0,
y: 0
},
{
diameter: 40,
x: 158,
y: 122
},
{
diameter: 86,
x: 274,
y: 214
},
{
diameter: 26,
x: 158,
y: 244
},
]
This exact array will produce the following result:
Now, after mocking this up, I got the crazy idea to add some gravity and bouncing. I wanted the bubbles to bounce like in this JSFiddle:
However, the only way I got the moving bubbles to work was by storing the information directly in state, as in the code below. (vy is the vertical speed of the ball.)
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
diameter: 0,
x: 0,
y: 0,
vy: 0,
clicked: false,
};
}
I use the following code to update the state of box in order to simulate the bouncing of the bubble:
fall(i){
this.setState({
y: this.state.y + i,
vy: this.state.vy + .01,
});
}
fallWrap(){
this.fall(this.state.vy);
this.u = setTimeout(this.fallWrap.bind(this), 1);
if(this.state.y >= 400 - (this.state.diameter/2)){
this.setState({
y: 400 - (this.state.diameter/2),
vy: -.9 * this.state.vy,
}, function(){
if(Math.abs(this.state.vy) < .2){
clearTimeout(this.u);
}
});
}
}
What I want to do is to store an array of multiple bubbles, like in the first JSfiddle, and have all the bubbles bounce around in the box like the second JS fiddle. This means updating value vy of multiple objects in the history array concurrently. I hope I have adequately described my needs. My central question is how can I use setstate to update a single value (vy) within each object stored within an array? For example, if I have
history =
[ {
diameter: 0,
x: 0,
y: 0,
vy: 0
},
{
diameter: 40,
x: 158,
y: 122,
vy: .5 //update this
},
{
diameter: 86,
x: 274,
y: 214,
vy: .4 //update this
},
{
diameter: 26,
x: 158,
y: 244
vy: .23 //update this
},
]
Then how I implement setState in a way that updates each vy? I know in React, state arrays should be immutable, so I am wondering if there is an established way to do this. The map function seems promising, but I don't know how to apply it here.
EDIT: Thanks everyone, I ended up solving my problem with Haken's solution. Here is a link to the JSFiddle
