Random number using React.js
Try this:
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
random: null
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const min = 1;
const max = 100;
const random = min + (Math.random() * (max - min));
this.setState({ random })
}
render() {
return (
<div>
<button value="Click me!" onClick={this.handleClick}>{this.state.random}</button>
</div>
);
}
}
React.render(<Button />, document.querySelector('#container'));
Remove all your logic from the render function and add it to the click handler method. Also the onClick is missing a curly bracket at the end. Finally you're not indicating the state property you're updating in the setState()
method.
This basically seems to do what you're after: https://codesandbox.io/s/98n9EkEOJ
This is the code just in case:
import React from 'react';
import { render } from 'react-dom';
class Button extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = { random: 0 };
}
handleClick() {
const min = 1;
const max = 100;
const rand = min + Math.random() * (max - min);
this.setState({ random: this.state.random + rand });
}
render() {
return (
<div>
<button onClick={this.handleClick.bind(this)}>Click</button>
<div>The number is: {this.state.random}</div>
</div>
);
}
}
render(<Button />, document.getElementById('container'));
- Firstly, you didn't set the state properly.
- Secondly, use arrow functions so you can avoid problematic binding.
- Thirdly, you didn't display the
random
value anywhere. - Lastly - you can move the
min
andmax
variables outside therender
function. Also the whole math logic responsible for rolling a random number can be moved into thehandleClick
function.
Working code:
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
random: null,
}
}
min = 1;
max = 100;
handleClick = () => {
this.setState({random: this.min + (Math.random() * (this.max - this.min))});
};
render() {
return (
<div>
<button onClick={this.handleClick}>Click me</button>
{this.state.random}
</div>
);
}
}