Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="root"></div>
              
            
!

CSS

              
                * {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

#root {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
}

.calculator {
  border: 2px solid black;
  padding: 1em;
  width: 400px;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  background: #f4dd4b;
}

#equation {
  border: 2px solid black;
  width: 100%;
  height: 1.5em;
  padding: 0.25em;
  border-bottom: none;
  background: black;
  color: #f6c616;
  text-align: right;
}

#display {
  border: 2px solid black;
  width: 100%;
  height: 2.5em;
  margin-bottom: 1em;
  padding: 0.5em;
  background: white;
  text-align: right;
}

.pad {
  border: 2px solid black;
  width: 100%;
  padding: 0.5em;
  background: #0c457a;
  color: white;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.key {
  border: 2px solid #115695;
  height: 64px;
  width: 60px;
  margin: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    border: 2px solid #f4dd4b;
  }
}

#equals,#clear{
  flex-grow: 1;
}
              
            
!

JS

              
                const keyArr = [
  {
    key: 7,
    id: "seven"
  },
  {
    key: 8,
    id: "eight"
  },
  {
    key: 9,
    id: "nine"
  },
  {
    key: "+",
    id: "add"
  },
  {
    key: "-",
    id: "subtract"
  },
  {
    key: 4,
    id: "four"
  },
  {
    key: 5,
    id: "five"
  },
  {
    key: 6,
    id: "six"
  },
  {
    key: "*",
    id: "multiply"
  },
  {
    key: "/",
    id: "divide"
  },
  {
    key: 1,
    id: "one"
  },
  {
    key: 2,
    id: "two"
  },
  {
    key: 3,
    id: "three"
  },
  {
    key: 0,
    id: "zero"
  },
  {
    key: ".",
    id: "decimal"
  },
  {
    key: "AC",
    id: "clear"
  },
  {
    key: "=",
    id: "equals"
  }
];

class Key extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div id={this.props.id} className="key" onClick={this.props.click}>
        {this.props.value}
      </div>
    );
  }
}

class Pad extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    let keys = this.props.keys.map((item, index) => {
      return <Key id={item.id} value={item.key} click={this.props.click} />;
    });
    return <div className="pad">{keys}</div>;
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      keyUsed: keyArr,
      display: ["0"],
      equation: [],
      restart:false,
      lastAnswer:false
    };
    this.handleClick=this.handleClick.bind(this);
    this.handleOperators=this.handleOperators.bind(this);
    this.handleNumbers=this.handleNumbers.bind(this);
    this.getAnswer=this.getAnswer.bind(this);
    this.handleDecimal=this.handleDecimal.bind(this);
  }

  handleOperators(input){
    let eq=this.state.equation;
    let currentEq = eq.join("");
    if(/[+*/]$/.test(currentEq)){   
      if(input=="-"){//[+/*] and users typed -
        this.setState({
          display:input,
          equation:[...eq,input]
        });
      }else{//[+/*] and users typed [+/*]
        this.setState({
          display:input,
          equation:[...eq.slice(0,eq.length-1),input]
        });
      }
    }else if(/-$/.test(currentEq)){//[+*/]- and users typed [+-*/]
      this.setState({
        display:input,
        equation:[...eq.slice(0,eq.length-2),input]
      });
    }else{//ends with number  
      this.setState({
        display:input,
        equation:[...eq,input]
      });
    }
  }

  handleNumbers(input){
    let dis = this.state.display;
    let eq=this.state.equation;
    //first number that users typed in  ||["+","*","/"].includes(dis[0])
    if(dis[0]=="0"){
      this.setState({
        display:input,
        equation:[input]
      });
      //numbers after operator
    }else if(["+","*","/"].includes(eq[eq.length-1])){
      this.setState({
        display:input,
        equation:[...eq,input]
      });  
    }else{//numbers more than one digit
      this.setState({
        display:[...dis,input],
        equation:[...eq,input]
      });
    }
  }

  getAnswer(){
    let eq=this.state.equation;
    let hasEquals = eq.indexOf("=");
    //continue calculation
    if(hasEquals>0){
      eq=eq.slice(hasEquals+1);
    }
    
    if(["+","*","/","-"].includes(eq[eq.length-1])){
      this.setState({
        display:"Error",
        equation:"Error",
        restart:true
      });
    }else{
      let calculation = new Function(`return ${eq.join("")}`);
      let answer = calculation();
      this.setState({
        display:answer,
        equation:[...eq,"=",answer],
        restart:true
      });
    }  

  }

  handleDecimal(input){
    let dis = this.state.display;
    let eq=this.state.equation;
    if(dis.includes(".")){return;}
    this.setState({
      display:[...dis,input],
      equation:[...eq,input]
    });
  }

  handleClick(e){
    let input=e.target.textContent;    

    //starting a new calculation
    if(this.state.restart){
      this.setState({
        display: ["0"],
        equation: [],
        restart:false
      });
    }

    switch(input){
      case "AC":
        this.setState({
          display: ["0"],
          equation: []
        });
        break;
      case ".":
        this.handleDecimal(input);
        break;
      case "+":
      case "*":
      case "/":
      case"-":
        this.handleOperators(input);
        break;
      case "=":
        this.getAnswer();
        break;
      default:
        this.handleNumbers(input);
    }
  }

  render() {
    return (
      <div className="calculator">
        <div id="equation">{this.state.equation}</div>
        <div id="display">{this.state.display}</div>
        <Pad keys={this.state.keyUsed} click={this.handleClick} />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

              
            
!
999px

Console