logo

Example: Component Composition

In this next example we do essentially similar things but we incorporate composition of components.
That is a huge benefit as we only need to write things once but can use it multiple times.
The idea is to have a select menu and depending on what is selected we will show a different set of checkboxes.

1. Start with the usual index.html-file where you define a div-Tag with an id of your choice.

    
<!-- index.html -->
<div id='myapp'></div>
<script type='module' src='app.js'></script>
    
    

2. In app.js, we set up our project as follows.

    
// app.js
import { RobJSApp } from './Rob.js'
import { Dropdown } from './Dropdown.js'

const app = new RobJSApp('myapp')
app.init('app')
app.defineStateVar('dropdown', 'All Dishes')
app.registerComponent(Dropdown, 'dropdown1', ['dropdown'])
app.initialRender(Dropdown, 'dropdown1')
    
    

3. Create a component called CheckboxesMeat and another component called CheckboxesVeggie.

    
// CheckboxesMeat.js
export const CheckboxesMeat = () => {
    return `
      <div>
        <input type='checkbox'>Beef</input>
        <input type='checkbox'>Pork</input>
      </div>
    `
};

// CheckboxesVeggie.js
export const CheckboxesVeggie = () => {
    return `
      <div>
        <input type='checkbox'>Couscous</input>
        <input type='checkbox'>Bulgur</input>
      </div>
    `
};
    
    

4. In the component called CheckboxesAll we combine both.

    
// CheckboxesAll.js
import { CheckboxesMeat } from './CheckboxesMeat.js'
import { CheckboxesVeggie } from './CheckboxesVeggie.js'

export const CheckboxesAll = () => {
    return `
      ${CheckboxesMeat()}
      ${CheckboxesVeggie()}
    `
};
    
    

5. Finally we create our select component (we called it Dropdown in this case) that decides which combination to render.

    
// Dropdown.js
import { CheckboxesAll } from './CheckboxesAll.js'
import { CheckboxesMeat } from './CheckboxesMeat.js'
import { CheckboxesVeggie } from './CheckboxesVeggie.js'

export const Dropdown = (id) => {

    let checkboxes
    if (app.state.dropdown === 'All Dishes') {
        checkboxes = `${CheckboxesAll()}`
    } else if (app.state.dropdown === 'Meat Dishes') {
        checkboxes = `${CheckboxesMeat()}`
    } else {
        checkboxes = `${CheckboxesVeggie()}`
    }
        
    return `
        <div id=${id}>
        <select onchange='app.updateState("dropdown", this.value)'>
            <option value='All Dishes' ${app.state.dropdown === 'All Dishes' && 'selected'}>All Dishes</option>
            <option value='Meat Dishes' ${app.state.dropdown === 'Meat Dishes' && 'selected'}>Meat Dishes</option>
            <option value='Veggie Dishes' ${app.state.dropdown === 'Veggie Dishes' && 'selected'}>Veggie Dishes</option>
        </select>
        ${checkboxes}
        </div>
    `
};
    
    

6. With a bit of styling it looks and works like this.

© - RobJS.org - All rights reserved