I'm a newbye in React. I created some simple Components to practice. For now, I'm using class Component (I want learn either class COmponent or function COmponent).
I would know if I projected properly my Components or if I could have a better setting:
My little application allow to increment a number of 1 by default, but I can change the increment picked from an input[type="range"]
Counter.js:
import { Component } from "react";
export default class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0, increment: props.step || 1 };
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount() {
this.setState({ count: this.state.count + this.props.step });
}
render() {
return (
<>
<p>Il contatore attualmente è {this.state.count}</p>
<button onClick={this.incrementCount}>Incrementa</button>
</>
);
}
}
StepCounter.js:
import { Component } from "react";
import Counter from "./Counter.js";
export default class StepCounter extends Component {
constructor(props) {
super(props);
this.state = { step: 1 };
this.changeStep = this.changeStep.bind(this);
}
changeStep(e) {
const clickedEl = e.target;
const choosedStep = Number(clickedEl.value);
this.setState({ step: choosedStep });
}
render() {
return (
<>
<input
type="range"
name=""
id=""
min={1}
max={10}
step={1}
value={this.state.step}
onChange={this.changeStep}
/>
<Counter step={this.state.step} />
</>
);
}
}
and App.js:
import { Component } from "react";
/* import Counter from "./Counter"; */
import StepCounter from "./StepCounter";
export default class App extends Component {
/* constructor(props) {
super(props);
} */
render() {
return <StepCounter></StepCounter>;
}
}
It works but, I repeat, I would know if I could improve the design.
prevState
to create the new state:setState((prevState) => ({stateName: prevState.stateName + 1 }))
\$\endgroup\$prevState
argument to make sure you use the latest state. You might not see any difference in your case. \$\endgroup\$onClick={(e) => this.incrementCount(e)}>
andonChange={(e) => this.changeStep(e)}
The reason is that you can remove thebind
statements. But this too has huge amounts of discussion about which is better :). And when you keep reading the end conclusion is to switch to hooks :/ \$\endgroup\$