Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  95] [ 6]  / answers: 1 / hits: 123453  / 7 Years ago, tue, july 18, 2017, 12:00:00

I wrote this code, but when I run it, I only get a blank page. What is wrong?
It does seem that I am close to the answer. I've tried everything, but it is still not working.



class Button extends React.Component {

constructor(props) {
super(props);
this.state = {
random: 0
}
}


render() {
var min = 1;
var max = 100;
var rand = min + (Math.random() * (max-min));
handleClick() {
this.setState ({this.state.random + this.rand})
}
return (
<div>
<button value=Click me! onClick={this.handleClick.bind(this)></button>
</div>
);

React.render(<Button />, document.querySelector('#container'));

}
}


JSFIDLLE: https://jsfiddle.net/1cban4oy/12/


More From » reactjs

 Answers
14

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'));

[#57041] Saturday, July 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;