22

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
  • There's no action binded to button. Commented Jul 18, 2017 at 19:53
  • Even with action binded, it did not work. Commented Jul 18, 2017 at 19:55
  • 2
    Your snippet is not valid JS. You've got your handleClick function inside render somehow, and React.render is inside the Button. Commented Jul 18, 2017 at 19:56
  • 1
    are you really trying to run JSX in the browser? are you transpiling it? what errors appear in your browser's console? Commented Jul 18, 2017 at 20:00
  • Help us reproduce your problem. JSX usually requires some HTML loading the page, etc. Please add everything you need to reproduce the issue to a well known javascript REPL (like jsbin) and give us the link to that. Commented Jul 18, 2017 at 20:06

7 Answers 7

29

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'));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

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

Comments

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.