123

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <html>
  <head>
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  </head>
  <body>
     <div id="app"></div>
  </body>
</html>

            
          
!
            
              body {
  font-size: 18px;
  font-family: 'Roboto', sans-serif;
  background: white;
}

.alertElement {
  color: white;
  position: fixed;
  background-color: #21252E;
  right: 10px;
  bottom: 10px;
  height: 300px;
  width: 300px;
  border-radius: 10px;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 4px 8px 16px 0 rgba(0,0,0,0.4);
  visibility: hidden;
  overflow: scroll;
  h2 {
    margin: 0px;
    margin-bottom: 10px;
  }

}

.container {
    width: 98vw;
  height: 98vh;
    display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper {
  box-shadow: 4px 8px 16px 0 rgba(0,0,0,0.4);
  background: #4A627A;
  padding: 20px;
  margin: 50px;
  min-width: 320px;
  min-height: 500px;
  transition: 1s;
  overflow: scroll;
  width: 70%;
  height: 70vw;
  max-width: 80vh;
  max-height: 80vh;
  position: relative;
  border-radius: 10px;
  .data-structure {
    position: absolute;
    color: white;
    padding: 10px;
    background-color: #21252E;
    box-shadow: 4px 8px 16px 0 rgba(0,0,0,0.4);
    top: 0px;
    right: 20px;
    border-radius: 10px;
    
  }
  .data-structure-button {
    position: absolute;
    top: 16px;
    right: 65px;
    .actual {
      position: fixed;
      box-shadow: 4px 8px 16px 0 rgba(0,0,0,0.4);
    
    width: 50px;
    height: 50px;
    box-sizing: border-box;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    cursor: pointer;
    z-index: 100;
    transition: 0.5s;
    }
  }
  
  .debug-button {
    position: absolute;
    top: 80px;
    right: 65px;
    .actual-debug {
      position: fixed;
      box-shadow: 4px 8px 16px 0 rgba(0,0,0,0.4);
    
      width: 50px;
      height: 50px;
      box-sizing: border-box;
      background: white;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      cursor: pointer;
      z-index: 100;
      transition: 0.5s;
    }
    .active-debug-button {
      transform: translateX(50px) rotate(-45deg);
    }
    .is-debugging {
      background-color: #80cbc4;
    }
  }
  
  .active-button {
    transform: translate(30px, -30px) rotate(30deg); /* Equal to rotateZ(45deg) */
  }
  
  .firstUL{
    transform: translateX(-90px);
  }
  h1{
    color: white;
  }
  .checkbox {
    display: flex;
    align-items: center;
    transform: translate(60px);

    margin: 10px;
    &__label {
      font-size: 24px;
      font-weight: 700;
      color: white;
    }
    &__icon {
      width: 50px;
      cursor: pointer;
      color: white;
      
    }
  }
}
            
          
!
            
              // Arbitrarily nested data
const toppingOptions = [
  {
    name: "Pepperoni",
    id: "pepperoni-id",
    subOptions: [
      {
        name: "Spicy",
        id: "spicy-id",
        subOptions: []
      },
      {
        name: "Regular",
        id: "regular-id",
        subOptions: []
      }
    ]
  },
  {
    name: "Chicken",
    id: "chicken-id",
    subOptions: [
      {
        name: "Buffalo",
        id: "buffalo-id",
        subOptions: [
          {
            name: "Mild",
            id: 'mild-id',
            subOptions: [],
          },
          {
            name: "Hot",
            id: 'hot-id',
            subOptions: [
              {
                name: 'Jalapeño',
                id: 'jalapeno-id',
                subOptions: []
              },
              {
                name: 'Cayenne',
                id: 'cayenne-id',
                subOptions: []
              }
            ],
          },
        ]
      },
      {
        name: "BBQ",
        id: 'bbq-id',
        subOptions: [],
      }
    ]
  },
]

// Root component -> Manages all app state
class App extends React.Component {    
  state = {
    selectedOptions: {}
  }

  render() {
     return (
       <div>
         <h1>Toppings</h1>
         <OptionsList 
           options={toppingOptions} 
           onChange={(selectedOptions) => this.setState({selectedOptions})}
           selectedOptions={this.state.selectedOptions} 
         />
       </div>
     )
  }
}

// Recursive component
const OptionsList = ({ options, selectedOptions, onChange }) => {
 
  const handleCheckboxClicked = (selectedOptionId) => {
    // is currently selected
    if(selectedOptions[selectedOptionId]){
      // remove selected key from options list
      delete selectedOptions[selectedOptionId]; 
    } else { // is not currently selected
      // Add selected key to optionsList
      selectedOptions[selectedOptionId] = {} 
    }
    // call onChange function given by parent
    onChange(selectedOptions) 
  }
  
  const handleSubOptionsListChange = (optionId, subSelections) => {
    // add sub selections to current optionId
    selectedOptions[optionId] = subSelections;
    // call onChange function given by parent
    onChange(selectedOptions);
  }
  
  return (
    <div>
      {options.map(option => (
        <ul>
          <Checkbox 
            selected={selectedOptions[option.id]} 
            label={option.name} 
            onChange={() => {handleCheckboxClicked(option.id)}}
           />
          {/* Base Case */}
          {(option.subOptions.length > 0 && selectedOptions[option.id]) &&
            <OptionsList
              options={option.subOptions}
              selectedOptions={selectedOptions[option.id]} 
              onChange={(subSelections) => handleSubOptionsListChange(option.id, subSelections)}
             />
          }
        </ul>
      ))}
    </div>
  )
}

// Dumb checkbox component, completly controlled by parent
const Checkbox = ({ selected, label, onChange }) => {
  return (
    <div>
      <div
        className="checkbox" 
        onClick={() => onChange(!selected)} 
      /> 
      <div className="label">{label}</div>
    </div>
  )
}







































































// Actual Code
class App2 extends React.Component {  
  constructor(props){
    super(props)
    this.state = {
      selectedOptions: {},
      codeShowing: false,
      debug: false
    }
  }
  
  button(){
    return (
      <div className="data-structure-button">
            <div onClick={() => this.setState({codeShowing: !this.state.codeShowing})} 
             className={classNames('fa', 'fa-2x', 'fa-code', 'actual', this.state.codeShowing && 'active-button')}>
           </div>
      </div>

      )
  }
  
  debugButton(){
    return (
      <div className="debug-button">
        <div onClick={() => this.setState({debug: !this.state.debug})} 
          className={classNames(
            'fa',
            'fa-2x',
            'fa-bug',
            'actual-debug',
            this.state.codeShowing && 'active-debug-button',
            this.state.debug && 'is-debugging')}>
        </div>
      </div>
    )
  }
  
  getDataStructureDisplay(){
    return (

        <pre className="data-structure"><code class="json">{JSON.stringify(this.state.selectedOptions, null, 3)}</code></pre>
    )
  }
  
  render() {
    const {selectedOptions} = this.state;
     return (
       <div className="container">
         <div className="wrapper">
           <h1>Toppings</h1>
           <OptionsList2 
             options={toppingOptions} 
             onChange={(selectedOptions) => {
               if(this.state.debug){
                 alert(`App Component:\n\nSetting selectedOptions state to\n\n${JSON.stringify(selectedOptions, null, 3)}\n\nThen re-rendering!`)
               }
               this.setState({selectedOptions})
             }}
             selectedOptions={selectedOptions} 
             isFirst={true}
             debug={this.state.debug}
             />
           {this.button()}
           {this.debugButton()}
           
           {this.state.codeShowing && this.getDataStructureDisplay()}
         </div>
       </div>
     )
  }
}
const OptionsList2 = ({ options, selectedOptions, onChange, isFirst, debug }) => {
 
  const handleCheckboxClicked = (selectedOptionId) => {
    let additionalText = `${selectedOptionId} is already selected, to deselect it we'll remove it from the current selectedOptions structure\n\n${JSON.stringify(selectedOptions, null, 3)}`;
    if(selectedOptions[selectedOptionId]){
      delete selectedOptions[selectedOptionId];
    } else {
      selectedOptions[selectedOptionId] = {}
      additionalText = `${selectedOptionId} is not currently selected, to select it we'll add "${selectedOptionId}: {}" to the current selectedOptions structure\n\n${JSON.stringify(selectedOptions, null, 3)}`;
    }
    if(debug){
      alert(`handleCheckboxClicked():\n\nClicked ${selectedOptionId} checkbox\n\n${additionalText}\n\nThen we'll call the current OptionList's onChange() function with the updated selectedOptions structure`);
    }
    onChange(selectedOptions)
  }
  
  const handleSubOptionsListChange = (optionId, subSelections) => {
    if(debug){
      alert(`handleSubOptionsListChange():\n\nThe onChange() function of ${optionId} was just called with the following sub options\n\n${JSON.stringify(subSelections, null, 3)}\n\nWe'll set "${optionId}" equal to that and pass the entire subOption structure at this level up to the parent.\n\n${JSON.stringify(selectedOptions, null, 3)}`);
    }
    selectedOptions[optionId] = subSelections;
    onChange(selectedOptions);
  }
  
  return (
    <div>
      {options.map(option => (
          <ul className={isFirst && "firstUL"}>
            <Checkbox2 
              selected={selectedOptions[option.id]} 
              label={option.name} 
              onChange={() => {handleCheckboxClicked(option.id)}}
            />
            {(option.subOptions.length > 0 && selectedOptions[option.id]) &&
              <OptionsList2 
                options={option.subOptions} 
                selectedOptions={selectedOptions[option.id]} 
                onChange={(subSelections) => handleSubOptionsListChange(option.id, subSelections)}
                debug={debug}
              />
            }
          </ul>
        )
      )}
    </div>
  )
}
const Checkbox2 = ({ selected, label, onChange }) => {
  return (
      <div className="checkbox">
      <div 
        className={
          classNames('fa', 'fa-2x', 'checkbox__icon', selected ? 'fa-check-square' : 'fa-square')} onClick={() => onChange(!selected)}></div>    
      <div className="checkbox__label">{label}</div>
    </div>
  )
}
ReactDOM.render(<App2 />, document.querySelector('#app'))

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console