css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <div class="container">
  <div id="app"></div>
  <div id="credit">Code by <a href="http://lukewalker.org" target="_blank">Luke Walker</a> for <a href="https://www.freecodecamp.com/challenges/build-a-recipe-box" target="_blank">this Free Code Camp project</a>.</div>
</div>
            
          
!
            
              .btn-lg
  margin: 5px

h1, h4
  text-align: center

.container
  position: relative
  #add
    position: absolute
    right: 15px
    
#credit
  text-align: center
  margin-top: 20px
  
            
          
!
            
              const {Button,
    Accordion,
    Panel,
    ListGroup,
    ListGroupItem,
    Modal,
    FormGroup,
    ControlLabel,
    FormControl,
    Glyphicon} = ReactBootstrap;

const defaultRecipes = [{name: "Spaghetti & Meat Sauce", ingredients: ["Spaghetti", "Meat Sauce"]}, {name: "Pumpkin Pie", ingredients: ["Crust", "Filling", "Whipped Cream"]}, {name: "Ice Cream", ingredients: ["Vanilla Ice Cream", "Chocolate Ice Cream", "Whipped Cream", "Chocolate Sauce", "Caramel"]}];

let recipes = localStorage.recipes ? JSON.parse(localStorage.recipes) : saveRecipes('recipes', defaultRecipes, 'Saving default recipes');

function saveRecipes(key, value, msg) {
  console.log(msg);
  localStorage.setItem(key, JSON.stringify(value));
  return JSON.parse(localStorage.getItem(key));    
}

class BaseComponent extends React.Component {
  _bind(...methods) {
    methods.forEach( (method) => this[method] = this[method].bind(this) );
  }
}

class App extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('actionPath', 'showModal');
    this.state = {recipes: recipes, showModal: false};
  }
  actionPath(actionKey) {
    if (actionKey === "close") {
      this.setState({showModal: false, editKey: ''});
    } else if (actionKey === "save") {
      this.setState({recipes: recipes, showModal: false, editKey: ''});
    } else {
      this.setState({showModal: true, editKey: actionKey});
    }
  }
  showModal() {
    this.setState({showModal: true, editKey: ''});
  }
  render() {
    return (
      <div>
        <h1>Recipe Box <Button id="add" bsStyle="btn btn-info" onClick={this.showModal}><Glyphicon glyph="plus" /> Add</Button></h1>
        <RecipeList recipes={this.state.recipes} onChange={this.actionPath}/>
        <AddModal editKey={this.state.editKey} show={this.state.showModal} onChange={this.actionPath} />
      </div>
    )
  }
}

class RecipeList extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('delete', 'edit');
  }
  delete(e) {
    const idx = e.target.id.substr(4);
    let newRecipes = recipes;
    newRecipes.splice(idx, 1);
    saveRecipes('recipes', newRecipes, 'Deleted recipe at index' + idx);
    ReactDOM.render(<App />, document.querySelector('#app'));
  }
  edit(e) {
    const idx = e.target.id.substr(5);
    this.props.onChange(idx);
  }
  render() {
    const recipePanels = this.props.recipes.map((recipe, idx) => 
      <Panel header={recipe.name} eventKey={idx}>
        <h4>Ingredients for {recipe.name}</h4>
        <IngredientList ingredients={recipe.ingredients} />
        <Button bsStyle="btn btn-lg btn-danger" id={"del-" + idx} onClick={this.delete}>Delete</Button>
        <Button bsStyle="btn btn-lg btn-info" id={"edit-" + idx} onClick={this.edit}>Edit</Button>
      </Panel>
    );
    return (
      <Accordion>
        {recipePanels}
      </Accordion>
    )
  }
}

class IngredientList extends BaseComponent {
  constructor(props) {
    super(props);
  }
  render() {
    const ingredientItems = this.props.ingredients.map(ingredient => <ListGroupItem>{ingredient}</ListGroupItem>)
    return (
      <ListGroup>
        {ingredientItems}
      </ListGroup>
    )
  }  
}

class AddModal extends BaseComponent {
  constructor(props) {
    super(props);
    this._bind('close', 'save');
  }
  close(e) {
    this.props.onChange(e.target.id);
  }
  save(e) {
    const newName = document.querySelector('#newName').value;
    const newIngredients = document.querySelector('#newIngredients').value.split(', ');
    let newRecipes = recipes;
    if (this.props.editKey !== '') {
      newRecipes[this.props.editKey] = {name: newName, ingredients: newIngredients};
    } else {
      newRecipes.push({name: newName, ingredients: newIngredients})
    }
 
    saveRecipes('recipes', newRecipes, 'Saving edited ' + newName);
    this.props.onChange(e.target.id);
    ReactDOM.render(<App />, document.querySelector('#app'));
  }
  render() {
    let title, name, ingredients
    if (this.props.editKey) {
      name = recipes[this.props.editKey].name;
      ingredients = recipes[this.props.editKey].ingredients.join(', ');
      title = "Editing " + name;
    } else {
      name = '';
      ingredients = '';
      title = "Add New Recipe";
    }
    return (
      <Modal show={this.props.show} onHide={this.close}>
        <Modal.Header>
          <Modal.Title>{title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <form>
            <FormGroup>
              <ControlLabel>Name:</ControlLabel>
              <FormControl componentClass="input" type="text" defaultValue={name} id="newName"/>
            </FormGroup>
            <FormGroup>
              <ControlLabel>Ingredients:</ControlLabel>
              <FormControl componentClass="textarea" id="newIngredients">{ingredients}</FormControl>
            </FormGroup>
          </form>
        </Modal.Body>
        <Modal.Footer>
          <Button bsStyle="btn btn-success" onClick={this.save} id="save" type="submit">Save</Button>
          <Button bsStyle="btn btn-warn" onClick={this.close} id="close">Cancel</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}


ReactDOM.render(<App />, 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.
Loading ..................

Console