18

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/

Damien
  • 1,582
  • 1
  • 13
  • 24

7 Answers7

27

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'));
Rodrigo
  • 1,638
  • 1
  • 15
  • 27
9
  • 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 and max variables outside the render function. Also the whole math logic responsible for rolling a random number can be moved into the handleClick 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>
    );
  }
}
kind user
  • 40,029
  • 7
  • 67
  • 77
  • 1
    I like the tip on using arrow functions -- thanks! I normally solve that using `this.handleClick = this.handleClick.bind(this);` in the constructor. The arrow method is much cleaner! – Dan Esparza Jul 19 '17 at 13:17
6

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'));
Andrii Starusiev
  • 7,564
  • 2
  • 28
  • 37
3

i think you need move this line

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

not only from render method but even from the class.

and you need to do some changes

so your code be like :

class Button extends React.Component {

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

   handleClick = () => {
      var min = 1;
      var max = 100;
      var rand =  min + (Math.random() * (max-min));
      this.setState ({this.state.random : rand})
   }

   render() {


    return (
      <div>
       <button value="Click me!" onClick={this.handleClick}> {this.state.random} </button>
       </div>
      );
  }


} 

React.render(<Button />, document.querySelector('#container'));
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
3

There is an easy way to create Random Number using

random-string

var x = randomString({
length: 8,
numeric: true,
letters: false,
special: false,

});

Here is the documentation for more details random-string

Saad Mirza
  • 1,154
  • 14
  • 22
0

Random number in an Array in React: [Math.floor(Math.random() * 20)]

Ahmedakhtar11
  • 1,076
  • 11
  • 7
0
import React, { useState } from "react";

const App = () => {
  const [num, setNum] = useState(0);

  function randomNumberInRange(min, max) {
    //  get number between min and max
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  const handleClick = () => {
    setNum(randomNumberInRange(1, 5));
  };

  return (
    <div>
      <h2>number is: {num}</h2>
      <button onClick={handleClick}>Generate random number</button>
    </div>
  );
};

export default App;
Avnish Jayaswal
  • 161
  • 1
  • 4