Rem calc util

by jonahe

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  max-width: 1000px;
}

.rem-calculator {
  padding: 20px;
  border-radius: 10px;
  background: #f98874;
}

label {
  display: block;
  margin-top: 5px;
  
}
label > * {
  display: inline-block;
  width: 40%;
}

label .unit {
  width: 10%;
  margin-left: 3px;
}

pre {
  border-radius: 10px 10px 0 0;
  margin: 5px 5px 0;
  padding: 20px;
  background: #566983;
  color: white;
  font-size: 14px;
  overflow: auto;
  tab-size: 2;
}

.preview {
  border-radius: 0 0 10px 10px;
  margin: 0px 5px 5px 5px;
  padding: 20px;
  background: #e8e8e8;
  min-height: 20vh;
}

b {
  display: block;
  font-size: 14px;
  border-bottom: 1px solid rgba(255,255,255,0.2);
}

React

/* code for adding styles to header, to get a simple preview of the calculated style
	https://stackoverflow.com/a/524721/4763083
*/

const useStyleString = styleString => {
	const
    head = document.head || document.getElementsByTagName('head')[0],
    styleEl = document.createElement('style');

  styleEl.type = 'text/css';
  styleEl.appendChild(document.createTextNode(styleString));

head.appendChild(styleEl);
}

/* actual calculator code */


const remCalc = (baseFontSize, sizeToConvertToRem) => {
	return (sizeToConvertToRem / baseFontSize).toFixed(3);
}
const unitlessCalc = (fontSizePx, lineHeightPx) => {
	return (lineHeightPx / fontSizePx).toFixed(3);
}

class RemCalculator extends React.Component {
  constructor(props) {
    super(props)
    const 
    	baseFontSize = 12, 
      pxValueToConvertToRem = 24,
      lineHeightPxValueToConvertToUnitless = 36;
      
    
    this.state = { 
    	baseFontSize, 
      pxValueToConvertToRem, 
      remResult: remCalc(baseFontSize, pxValueToConvertToRem),
      lineHeightPxValueToConvertToUnitless,
      unitlessLineHeightResult: unitlessCalc(pxValueToConvertToRem, lineHeightPxValueToConvertToUnitless)
    };
    this.handleStateChange = this.handleStateChange.bind(this);
    this.updateCalculations = this.updateCalculations.bind(this);
    this.getStyleSheetString = this.getStyleSheetString.bind(this);
    
    useStyleString(this.getStyleSheetString());
  }
  componentDidUpdate() {
  	useStyleString(this.getStyleSheetString());
  }
  
  handleStateChange(key, value) {
  	this.setState({[key]: value});
    this.updateCalculations(() => this.getStyleSheetString());
    
  }
  updateCalculations(callback) {
  	this.setState((state, props) => {
    	const {baseFontSize, pxValueToConvertToRem, lineHeightPxValueToConvertToUnitless} = state;
      
    	return { 
      	baseFontSize, 
        pxValueToConvertToRem, 
        remResult: remCalc(baseFontSize,pxValueToConvertToRem),
        unitlessLineHeightResult:...