In this example we change the appearance of the UI based on the current state.
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.
Notice that if we do not use a wrapper component as an entry point but a stateful component directly, we must pass its id to the initialRender function as well.
// app.js
import { RobJSApp } from './Rob.js'
import { Counter } from './Counter.js'
const app = new RobJSApp('myapp')
app.init('app')
app.defineStateVar('count', 0)
app.registerComponent(Counter, 'counter1', ['count'])
app.initialRender(Counter, 'counter1')
3. Create a component called Counter.js and in there we create a style variable that depends on the current count value.
// Counter.js
const Counter = (id) => {
let style = 'padding: 5px; border-radius: 5px;'
if(app.state.count >= 3 && app.state.count < 6){
style = style += 'background-color: green;'
} else if (app.state.count >= 6){
style = style += 'background-color: red;'
} else {
style = style += 'background-color: yellow;'
}
return `
<div id=${id}>
<p style='${style}'>I turn green after count is 3 and red after count is 6.</p>
<button onclick='app.updateState("count", app.state.count - 1)'>-</button>
${app.state.count}
<button onclick='app.updateState("count", app.state.count + 1)'>+</button>
</div>
`;
};
4. With a bit of styling of the buttons it looks and works like this.
© - RobJS.org - All rights reserved