React setState in onClick method not updating the DOM - javascript

I'm developing a simple game fight animation using react. To start the fight, I've a button with onClick event: onClick={this.fight.bind(this)}. Now I want to update some state variable in the anytime something changes like this:
import React, { Component } from 'react';
import { ProgressBar, Row, Col } from 'react-bootstrap';
const playerA = {
_id: 1,
name: "playerA name",
life: 100,
speed: 50,
}
const playerB = {
_id: 1,
name: "playerB name",
life: 100,
speed: 40,
}
export default class App extends Compornent {
constructor() {
super();
this.state={
playerA : playerA ,
playerB : playerB ,
aLife: 100,
bLife: 100,
};
this.fight = this.fight.bind(this);
};
fight(a,b){
lifeA=this.state.playerA.live;
lifeB=this.state.playerB.live;
speedA=this.state.playerA.speed;
speedB=this.state.playerB.speed;
dmg = 10
while (lifeA>0 && lifeB>0) {
if (speedA > speedb) {
lifeA = lifeA - dmg;
setTimeout(() => {
this.setState({ aLife: lifeA });
}, 1000);
speedB = speedB + 10;
} else {
lifeB = lifeB - dmg;
setTimeout(() => {
this.setState({ bLife: lifeA });
}, 1000);
speedA = speedA + 10;
}
}
render() {
return (
<Row>
<ProgressBar bsStyle="success" now={this.state.aLife} srOnly/>
<ProgressBar bsStyle="success" now={this.state.bLife} srOnly/>
</Row>
<Row>
<Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>
</Row>
);
}
}
My expectation is to see the progress bars beeing update every 1 second. But it only updates once. When the fight funtion has finisched beein executed.

refer to the ReactJs official documents, you don't have to bind this again in the render function, since you have already done the binding in Constructor Function
<Button bsStyle="danger" bsSize="large" onClick={this.fight.bind(this)}>Start Fight</Button>
should be
<Button bsStyle="danger" bsSize="large" onClick={this.fight}>Start Fight</Button>

I finally get this done by completely rewriting the while loop using setInterval whith a bool condition: ((npcPlayerLife > 0) && (advPlayerLife > 0)) and then stop when the condition in no more meet.
I have this help someone.

Related

Is there any way to change state inside render in React js?

So I am working on a dice application where I have a class component for setting the number of dice and sides of each dice with up and down buttons. My problem is that each time I press up or down button to set number of sides or number of dice, an array of random numbers gets created and displays on screen. However, I want the value to display only when the roll button is clicked.
So is there a way I can change the state of displayDice to false after I have created the array in the render, so that it only becomes true when I click roll button again
You can move logic to componentDidMount. Render is to just render UI. No business logic. It will handle event and delegate to state.
Move generate random to parent component, pass method rollChange from parents to child.
// Dice component
class SideAndDice extends React.Component {
constructor(props) {
super(props);
this.state = { sides: 6, dice: 1, randoms: this.generateRandom() };
}
increaseDice() {
this.setState({ dice: this.state.dice + 1 });
}
decreaseDice() {
if (this.state.dice > 1) {
this.setState({ dice: this.state.dice - 1 });
}
}
increaseSides() {
this.setState({ sides: this.state.sides + 1 });
}
decreaseSides() {
if (this.state.sides > 2) {
this.setState({ sides: this.state.sides - 1 });
}
}
generateRandom() {
let randoms = [];
for (var i = 0; i < this.state.dice; i++) {
var randomValue = Math.floor(Math.random() * this.state.sides + 1);
randoms.push(randomValue);
}
return randoms;
}
onRollDice() {
this.setState({ randoms: this.generateRandom() });
}
render() {
return (
<div>
<h1>Number of Sides</h1>
<h2>{this.state.sides}</h2>
<button onClick={this.increaseSides.bind(this)}>Up</button>
<button onClick={this.decreaseSides.bind(this)}>Down</button>
<h1>Number of Dice</h1>
<h2>{this.state.dice}</h2>
<button onClick={this.increaseDice.bind(this)}>Up</button>
<button onClick={this.decreaseDice.bind(this)}>Down</button>
<CreateScores
randoms={this.state.randoms}
rollChange={this.rollChange.bind(this)}
/>
</div>
);
}
}
class CreateScores extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onRollDice.bind(this)}>Roll</button>
<br />
<br />
{this.props.randoms.map(random => (
<Dice key={i} diceNumber={randomValue} />
))}
</div>
);
}
}

Not rendering JSX from function in React

The function is getting the value of a button click as props. Data is mapped through to compare that button value to a key in the Data JSON called 'classes'. I am getting all the data correctly. All my console.logs are returning correct values. But for some reason, I cannot render anything.
I've tried to add two return statements. It is not even rendering the p tag with the word 'TEST'. Am I missing something? I have included a Code Sandbox: https://codesandbox.io/s/react-example-8xxih
When I click on the Math button, for example, I want to show the two teachers who teach Math as two bubbles below the buttons.
All the data is loading. Just having an issue with rendering it.
function ShowBubbles(props){
console.log('VALUE', props.target.value)
return (
<div id='bubbles-container'>
<p>TEST</p>
{Data.map((item,index) =>{
if(props.target.value == (Data[index].classes)){
return (
<Bubble key={index} nodeName={Data[index].name}>{Data[index].name}
</Bubble>
)
}
})}
</div>
)
}
Sandbox Link: https://codesandbox.io/embed/react-example-m1880
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
const circleStyle = {
width: 100,
height: 100,
borderRadius: 50,
fontSize: 30,
color: "blue"
};
const Data = [
{
classes: ["Math"],
name: "Mr.Rockow",
id: "135"
},
{
classes: ["English"],
name: "Mrs.Nicastro",
id: "358"
},
{
classes: ["Chemistry"],
name: "Mr.Bloomberg",
id: "405"
},
{
classes: ["Math"],
name: "Mr.Jennings",
id: "293"
}
];
const Bubble = item => {
let {name} = item.children.singleItem;
return (
<div style={circleStyle} onClick={()=>{console.log(name)}}>
<p>{item.children.singleItem.name}</p>
</div>
);
};
function ShowBubbles(props) {
var final = [];
Data.map((item, index) => {
if (props.target.value == Data[index].classes) {
final.push(Data[index])
}
})
return final;
}
function DisplayBubbles(singleItem) {
return <Bubble>{singleItem}</Bubble>
}
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
json: [],
classesArray: [],
displayBubble: true
};
this.showNode = this.showNode.bind(this);
}
componentDidMount() {
const newArray = [];
Data.map((item, index) => {
let classPlaceholder = Data[index].classes.toString();
if (newArray.indexOf(classPlaceholder) == -1) {
newArray.push(classPlaceholder);
}
// console.log('newArray', newArray)
});
this.setState({
json: Data,
classesArray: newArray
});
}
showNode(props) {
this.setState({
displayBubble: true
});
if (this.state.displayBubble === true) {
var output = ShowBubbles(props);
this.setState({output})
}
}
render() {
return (
<div>
{/* {this.state.displayBubble ? <ShowBubbles/> : ''} */}
<div id="sidebar-container">
<h1 className="sidebar-title">Classes At School</h1>
<h3>Classes To Search</h3>
{this.state.classesArray.map((item, index) => {
return (
<button
onClick={this.showNode}
className="btn-sidebar"
key={index}
value={this.state.classesArray[index]}
>
{this.state.classesArray[index]}
</button>
);
})}
</div>
{this.state.output && this.state.output.map(item=><DisplayBubbles singleItem={item}/>)}
</div>
);
}
}
ReactDOM.render(<Sidebar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The issue here is ShowBubbles is not being rendered into the DOM, instead (according the sandbox), ShowBubbles (a React component) is being directly called in onClick button handlers. While you can technically do this, calling a component from a function will result in JSX, essentially, and you would need to manually insert this into the DOM.
Taking this approach is not very React-y, and there is usually a simpler way to approach this. One such approach would be to call the ShowBubbles directly from another React component, e.g. after your buttons using something like:
<ShowBubbles property1={prop1Value} <etc...> />
There are some other issues with the code (at least from the sandbox) that you will need to work out, but this will at least help get you moving in the right direction.

How can a React method bound in constructor lose it's boundedness when passed as parameter?

Here is the codesandbox for this question: https://codesandbox.io/s/rdg-grouping-81b1s
I am using React-Data-Grid to render a table. I render a ReactDataGrid with two columns, and When you click on the text GROUP in a header cell you group by that column.
To be able to have a custom header cell with that text GROUP, I use the property headerRenderer in the object defining the columns.
The value passed to this property is a function that takes an onClick handler as parameter, and returns a functional React component that uses that onClick handler.
The onClick parameter is just a method on the original React component, and it is bound in the component's constructor.
As you can see, I am using this headerRenderer property twice, once for each column. However, for the first column, I bind the parameter function to the React component again. For the second column I do not, and this generates an error when I try to click the GROUP text for this column. See error image further below.
My question is: why do I have to bind given that I've already bound the function in the constructor?
import React from 'react';
import './App.css';
import ReactDataGrid from 'react-data-grid';
import { Data } from 'react-data-grid-addons';
const HeaderRowRenderer = function(props) {
return (
<div
style={{
backgroundColor: 'red',
paddingLeft: 10,
height: '100%',
padding: 0,
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
}}
>
<span>{props.column.name}</span>
<span onClick={props.onClick}>GROUP</span>
</div>
);
};
const HeaderRenderer = function(groupBy, onClick) {
return function(props) {
return (
<HeaderRowRenderer
{...props}
onClick={function() {
onClick(groupBy);
}}
/>
);
};
};
const rows = [{ productname: 'Beef', quantity: 5 }, { productname: 'Veggies', quantity: 10 }];
class App extends React.Component {
columns = [
{
key: 'productname',
name: 'Product',
width: 200,
headerRenderer: HeaderRenderer('productname', this.groupBy.bind(this)),
},
{
key: 'quantity',
name: 'Quantity',
headerRenderer: HeaderRenderer('quantity', this.groupBy),
},
];
constructor(props) {
super(props);
this.state = {
groupBy: new Set([]),
};
this.groupBy = this.groupBy.bind(this);
}
groupBy(group) {
const newSet = new Set(this.state.groupBy);
if (newSet.has(group)) {
newSet.delete(group);
} else {
newSet.add(group);
}
this.setState({ groupBy: newSet });
}
render() {
const groupBy = Array.from(this.state.groupBy);
// const rows = this.props.orderItems;
const groupedRows = Data.Selectors.getRows({
rows: rows,
groupBy,
});
return (
<div>
<ReactDataGrid
columns={this.columns}
rowGetter={i => groupedRows[i]}
rowsCount={groupedRows.length}
minHeight={650}
/>
</div>
);
}
}
export default App;
I looked at the code for React-Data-Grid, and I believe that the headerRenderer prop is called as below:
getCell() {
const { height, column, rowType } = this.props;
const renderer = this.props.renderer || SimpleCellRenderer;
if (isElement(renderer)) {
// if it is a string, it's an HTML element, and column is not a valid property, so only pass height
if (typeof renderer.type === 'string') {
return React.cloneElement(renderer, { height });
}
return React.cloneElement(renderer, { column, height });
}
return React.createElement(renderer, { column, rowType });
}
I'm not very familiar with the ways in which a function that was bound using bind and then is passed around can lose this boundedness. Does this happen as a result of React.cloneElement, or what could be the cause of it?

Custom component not getting rendered properly on this basic ReactJS app

I have a very basic ReactJS app which uses Redux which contains the following components:
PanelMaterialSize > Select
/src/controls/PanelMaterialSize/PanelMaterialSize.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './PanelMaterialSize.scss';
import Select from '../Select/Select';
import { setThemeList } from '../../store/AppConfig/actions';
class PanelMaterialSize extends Component {
componentDidMount() {
this.n = 1;
setInterval(() => {
let themeList = [
{ value: this.n, text: 'Option ' + this.n },
{ value: this.n + 1, text: 'Option ' + (this.n + 1) },
{ value: this.n + 2, text: 'Option ' + (this.n + 2) },
];
this.props.setThemeList(themeList);
this.n += 3;
}, 1000);
}
render() {
return (
<div className="partial-designer-panel-material-size">
<div>
<div className="label-input">
<div className="label">MATERIAL</div>
<div className="input">
<Select data={this.props.themeList} style={{ width: '100%' }} />
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (appState) => {
return {
themeList: appState.appConfig.themeList,
}
}
const mapDispatchToProps = (dispatch) => {
return {
setThemeList: (themeList) => dispatch(setThemeList(themeList)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(PanelMaterialSize);
In my opinion the Redux logic is fine because I have tested by doing couple of things.
My problem is that when the render(...) method of: PanelMaterialSize gets called, the component: Select doesn't get rendered with the new data (which changes every one second).
Here you have a Codesandbox.io you can play with (preferable use Chrome):
https://codesandbox.io/s/03mj405zzv
Any idea on how to get its content changed properly?
If possible, please, provide back a new Codesandbox.io with your solution, forked from the previous one.
Thanks!
the problem is here in your select component.
you are passing initially empty array and checking your component with this.state.data props, next time reducer change your this.state.data will not update the data. because you initialize in constructor. constructor only invoke once when component mount.
SOLVED DEMO LINK
The Problem is in your select render method:
render() {
let data = this.state[this.name];
return (
<div className="control-select" {...this.controlProps}>
<div className="custom-dropdown custom-dropdown--grey">
<select className="custom-dropdown__select custom-dropdown__select--grey">
//change data with this.props.data
{this.props.data.length > 0 &&
this.props.data.map((elem, index) => {
return (
<option value={elem.value} key={index}>
{elem.text}
</option>
);
})}
</select>
</div>
</div>
);
}

onClick event doesn't act in ReactJS

I have a react code where I have onClicke event. I suppose to get implementation of function(someFunction). I didn't get any error running this code, everything else works. I guess the problem can be in function. The React code is
class Hello extends Component {
constructor() {
super();
this.num = { number: 4 };
this.someFunction = this.someFunction.bind(this);
}
someFunction() { this.setState({ number: this.num.number + 3 }); }
render() {
const coco = {
color: 'blue',
background: 'yellow',
width: '200px',
height: '200px',
padding: 'lem'
};
return (<div style={coco} onClick={this.someFunction}>
<p style={coco} onClick={this.someFunction}> bly blya
Hello {this.props.name} </p>
<p style={coco} onClick={this.someFunction} >
Current count: {this.num.number + 3}
</p>
</div>)
}
}
render(<Hello/>, document.getElementById('container'));
actually it is working just fine , your component isn't updating because it doesn't depend on state in fact you havne't defined any state in the constructor which might be a typo ..
import React , {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
constructor() {
super();
// defining state
this.state = { number: 4 };
this.someFunction = this.someFunction.bind(this);
}
someFunction() {
//chnaging state case re-render for component
this.setState({number: this.state.number + 3 });
}
render() {
const coco = {
color: 'blue',
background: 'yellow',
width: '200px',
height: '200px',
padding: 'lem'
};
return (
<div style={coco} onClick={this.someFunction}>
<p style={coco} onClick={this.someFunction}> bly blya
Hello {this.props.name} </p>
<p style={coco} onClick={this.someFunction} >
Current count: {this.state.number + 3 /*need to use state here . */}
</p>
</div>
)
}
}
ReactDOM.render(<Hello/>, document.getElementById('container'));
You should replace:
Current count: {this.num.number + 3}
with:
Current count: {this.state.num.number + 3}
Instead of defining this.num, you should define the initial state of your component in the constructor:
this.state = {
number: 4,
};
Your function gets correctly called on the click callback, however the logic of updating the state doesn't work because it always returns the same state. this.num.number always has a value of 4 and thus your state will always have a value of 7 after calling setState.
You can use the previous state to calculate the new state like this:
this.setState((prevState) => {
return {
number: prevState.number + 3
};
});
See this JSFiddle

Categories

Resources