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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <!-- 
// -----------------
// Github project: https://github.com/Alvaro07/react-calculator
// -----------------
 -->

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

CSS

              
                // -----------------
// Github project: https://github.com/Alvaro07/react-calculator
// -----------------

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


:root {
--dark-gray: #333;
--medium-gray: #383838;
--gray: #5F6A72;
--light-gray: #707679;
--dark-green: #18597D;
--yellow: #e3b54d;
--purple: #4A4857;
--navy: #505C70;
--blue: #26A0CD;
--light-blue: #47abd0;
--orange: #e2725d;
--light-orange: #e87d68;
}


html, 
body,
.app {
	height: 100%;
}

.app-wrap {
	height: 100%;
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	background-image: linear-gradient(15deg, #13547a 0%, #80d0c7 100%);
}


.calculator {
	width: 320px;
	height: 445px;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	grid-template-rows: 1fr 30px repeat(5, 1fr);
	grid-gap: 2px;
	background-color: var(--dark-gray);
	border: 1px solid var(--dark-gray);
	border-top-left-radius: 15px;
	overflow: hidden;
	box-shadow: 6px 6px 15px 1px rgba(#18597D, .5);
	
	&__result {
		grid-column: 1 / span 4;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		overflow: hidden;
		background-color: var(--dark-gray);
		text-overflow: ellipsis;
    	white-space: nowrap;
		
		font-family: 'Roboto', sans-serif;
		font-size: 32px;
		font-weight: 500;
		color: white;
		padding-right: 30px;
		
		
	}
	
	&__history {
		grid-column: 1 / span 4;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		position: relative;
		
		font-size: 14px;
		font-family: 'Roboto', sans-serif;
		color: white;
		font-weight: 700;
		
		background-color: var(--medium-gray);
		padding:0 15px 0 60px;
		
		li {
			padding-left: 5px;
		}
		
		&::before {
			content: 'HISTORY';
			position: absolute;
			left: 10px;
			bottom: 9px;
			font-size: 10px;
			font-weight: 500;
			color: var(--yellow);
		}
		
		&.is-hide::before {
			display: none
		}
		
	}
	
	&__btn {
		font-family: 'Roboto', sans-serif;
		font-size: 32px;
		font-weight: 700;
		text-shadow: 1px 1px 0px rgba(51, 51, 51, 1);

		border: none;
		background-color: var(--purple);
		color: white;
		cursor: pointer;
		transition: .1s all ease;
		outline: none;
		position: relative;
		padding: 0;
		
		&:hover {
			background-color: var(--navy);
		}
		
		&:before {
			content: '';
			display: block;
			position: absolute;
			top: 0;
			width: 100%;
			height: 100%;
			border: 1px solid white;
			opacity: 0;
		}
		
		&:focus {
			&:before {
				animation: border-animation 0.2s ease-out;
			}
		}
		
		// Variants
		
		&--operator {
			background: var(--gray);
			
			&:hover {
				background-color: var(--light-gray)
			}
		}
		
		&--cero {
			grid-column: 1 / span 2;
		}
		
		&--empty {
			pointer-events: none;
		}
		
		&--reset {
			background: var(--blue);
			grid-column: 1 / span 2;
			
			&:hover {
				background-color: var(--light-blue);
			}
		}
		
		&--equal {
			background: var(--orange);
			grid-column: 3 / span 2;
			
			&:hover {
				background-color: var(--light-orange);
			}
		}
	}
}


@keyframes border-animation {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
              
            
!

JS

              
                // -----------------
// Github project: https://github.com/Alvaro07/react-calculator
// -----------------


// -----------------
// Calculator's buttons

const Button = (props) => {
	return 	<button className={`calculator__btn ${props.extraClass}`} onClick={props.onClick}>{props.children}</button>
}

Button.defaultProps = {
	extraClass: ''
};


// -----------------
// Calculator component

class Calculator extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      operatorA: '',
      operatorB: '',
      operator: null,
			history: []
    }
  }
	
	
	//  ----------------
	//	Numeric function 
	
  handleNumber = (e, number) => {
		e.target.blur();
		
		if ( this.state.operator === '=' ) {
			this.setState({ 
				operatorA: parseFloat(number).toString(),
				operator: null,
				history: []
			})
			
		} else if ( !this.state.operator) {
			this.setState({ operatorA: parseFloat(this.state.operatorA + number).toString() });
			
		} else {
			this.setState({ operatorB: parseFloat(this.state.operatorB + number).toString() });
		}
		
  }
	
	
	//  ----------------
	//	Operator function
	
  handleOperator = (e, operator) => {
		e.target.blur();

		if ( this.state.operatorA === ''){
			return
		}

		
    if (this.state.operator === null){
			
			const newHistory = [...this.state.history, ...[parseFloat(this.state.operatorA).toString(), operator]];
			this.setState({ 
				operator: operator,
				history: newHistory
			});
			
		} else if ( this.state.operator === '=') { 
			
			const newHistory = [...this.state.history, operator];
			this.setState({ 
				operator: operator,
				history: newHistory
			});
			
		} else {
			
			let plusResult;
			let opA = parseFloat(this.state.operatorA);
			let opB = this.state.operatorB !== '' ? parseFloat(this.state.operatorB) : 0;
			
			switch (this.state.operator) {
				case '+': 
					plusResult = opA + opB;
					break;

				case '-':
					plusResult = opA - opB;
					break;

				case '*':
					plusResult = opA * opB;
					break;

				case '/':
					plusResult = opA / opB;
					break;
				
				default:
					break
			}
			
			const newHistory = this.state.operatorB !== '' ?
						[...this.state.history, ...[parseFloat(this.state.operatorB).toString(), operator]] :
						this.state.history
			
			this.setState({ 
				operator: operator,
				operatorA: plusResult.toString(),
				operatorB: '',
				history: newHistory
			});
			
		}
  }
	
	//  ----------------
	//	Result function

	handleDecimal = (e) => {
		e.target.blur();

		if ( this.state.operatorA === ''){
			return
		}

		if ( this.state.operatorB === ''){
			this.setState({ operatorA: this.state.operatorA.concat('.') });
		} else {
			this.setState({ operatorB: this.state.operatorB.concat('.') });
		}

	}
	
	//  ----------------
	//	Result function
	
  handleResult = (e, operator) => {
		e.target.blur();

		if ( this.state.operatorB === ''){
			return
		}
		
    const opA = parseFloat(this.state.operatorA);
		const opB = parseFloat(this.state.operatorB);
    let finalResult;

    switch (this.state.operator) {
      case '+':
        finalResult = Math.round((opA + opB) * 100) / 100;
        break;

      case '-':
        finalResult = Math.round((opA - opB) * 100) / 100;
        break;

      case '*':
        finalResult = Math.round((opA * opB) * 100) / 100;
        break;

      case '/':
        finalResult = Math.round((opA / opB) * 100) / 100;
				break;
			
			default:
				break
    }
		
		const newHistory = [...this.state.history, ...[parseFloat(this.state.operatorB).toString(), operator, finalResult.toString()]];
    this.setState({ 
      operatorA: finalResult.toString(),
      operatorB: '',
      operator: operator,
			history: newHistory
    });

  }
  
	
	//  ----------------
	//	Reset function
	
  handleReset = (e, operator) => {
		e.target.blur();
		
    this.setState({
      operatorA: '',
      operatorB: '',
      operator: null,
			history: []
    })
  }


  render() {
		
		let result = '0';

    if ( this.state.operatorB !== '') {
      result = parseFloat(this.state.operatorB).toString();
			
    } else if ( this.state.operatorA !== ''){
      result = parseFloat(this.state.operatorA).toString();
			
    } else {
			result = parseFloat(result).toString();
			
    }

    return (

			<div className="calculator">
				<span className="calculator__result" >{result}</span>
				
				<ul className={`calculator__history ${!this.state.history.length > 0 ? 'is-hide' : ''}`} >
						{this.state.history != null ? 
							this.state.history.map((value, i) => <li key={i}>{value}</li>) : null}
				</ul>

				<Button onClick={(e) => this.handleNumber(e, 1)}>1</Button>
				<Button onClick={(e) => this.handleNumber(e, 2)}>2</Button>
				<Button onClick={(e) => this.handleNumber(e, 3)}>3</Button>
				<Button onClick={(e) => this.handleOperator(e, '+')} extraClass='calculator__btn--operator'>+</Button>

				<Button onClick={(e) => this.handleNumber(e, 4)}>4</Button>
				<Button onClick={(e) => this.handleNumber(e, 5)}>5</Button>
				<Button onClick={(e) => this.handleNumber(e, 6)}>6</Button>
				<Button onClick={(e) => this.handleOperator(e, '-')} extraClass='calculator__btn--operator'>-</Button>

				<Button onClick={(e) => this.handleNumber(e, 7)}>7</Button>
				<Button onClick={(e) => this.handleNumber(e, 8)}>8</Button>
				<Button onClick={(e) => this.handleNumber(e, 9)}>9</Button>
				<Button onClick={(e) => this.handleOperator(e,'*')} extraClass='calculator__btn--operator'>X</Button>

				<Button onClick={(e) => this.handleNumber(e, 0)} extraClass='calculator__btn--cero'>0</Button>
				<Button onClick={(e) => this.handleDecimal(e)}>.</Button>
				<Button onClick={(e) => this.handleOperator(e,'/')} extraClass='calculator__btn--operator'>/</Button>

				<Button onClick={(e) => this.handleReset(e)} extraClass='calculator__btn--reset'>C</Button>
				<Button onClick={(e) => this.handleResult(e,'=')} extraClass='calculator__btn--equal'>=</Button>
			</div>
			
    );
  }
}


// app.js
// App component

const App = () => {
	return(
		<div className="app-wrap">
			<Calculator />
		</div>	
	)
}
	

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

              
            
!
999px

Console