Skip to main content
1 of 2

Dice-rolling tool

I am an experienced programmer, but a complete beginner with React. My goal is to teach myself React.

I've made a simple die-roller application. The application presents a drop-down, and the user can choose what die to roll (e.g. a d6 is a six-sided die). When the user clicks "roll", an appropriate random number is generated and displayed.

The app is working fine, but I would be grateful to know whether I've written genuinely "React-y" code; whether it's structured properly, whether I have got the naming conventions right, etc.

Some specific questions: is the "Dice" constant declared in the right place/way? Should the "option" elements be full React components? Should the "button" be a full React component?

Thank you.

import React, { Component } from 'react';
import './App.css';

const Dice = ["4", "6", "8", "10", "12", "20"];

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      outcome: null,
      sides: null
    };
    this.handleClick = this.handleClick.bind(this);
    this.setSides = this.setSides.bind(this);
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          Die roller
        </header>
        
        <DieChooser dice={Dice} setSides={this.setSides}></DieChooser>
        <button onClick={this.handleClick}>Roll</button>
        <Result outcome={this.state.outcome} />

      </div>
    );
  }

  setSides(s) {
    this.setState({sides: s});
  }

  handleClick() {
    const rolled = Math.floor(Math.random() * (this.state.sides)) + 1;
    this.setState({ outcome: rolled })
  }
}

class DieChooser extends Component {

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.props.setSides(props.dice[0]);
  }

  handleChange(e) {
    this.props.setSides(e.target.value)
  }

  render() {
    return (
      <select onChange={this.handleChange}>
        {this.props.dice.map((die) =>
          <option key={die} value={die}>d{die}</option>
        )}
      </select>
    )
  }
}

function Result (props) {
  return (
    <p>{props.outcome}</p>
  )
}

export default App;