Random number using React.js

Viewed 108154

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/

7 Answers

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

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

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;
Related