-
hi, I'm trying to add multi select buttons that are highlighted based on if they match a passed in setting like this, it doesn't work though. is there a way to do this with vanjs? const MultiButton = ({ setting, value, text, onclick }) => {
const highlighted = van.derive(() => (van.val(value) === van.val(setting)))
return button({ style: () => `background-color: ${highlighted ? 'blue' : 'red'};`, onclick }, text)
}
const state = vanX.reactiv({period:'lifetime})
div(
MultiButton({ onclick: () => state.period = 'lifetime', text: 'Lifetime', value: 'lifetime', setting: state.period }),
MultiButton({ onclick: () => state.period = 'monthly', text: 'Subscription', value: 'monthly', setting: state.period }),
MultiButton({ onclick: () => state.period = 'yearly', text: 'Yearly', value: 'yearly', setting: state.period }),
), |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
For the derived state to be reactive to the field updates of the reactive object, you need to "access" the field inside the binding function, instead of accessing the field outside the binding function and pass-in the result into the binding function (see the caveat here). For your example to work, you need to change the value of btw: another thing needs to fix is to change const MultiButton = ({ setting, value, text, onclick }) => {
const highlighted = van.derive(() => (van.val(value) === setting()))
return button({ style: () => `background-color: ${highlighted.val ? 'blue' : 'red'};`, onclick }, text)
}
const state = vanX.reactive({period:'lifetime'})
div(
MultiButton({ onclick: () => state.period = 'lifetime', text: 'Lifetime', value: 'lifetime', setting: () => state.period }),
MultiButton({ onclick: () => state.period = 'monthly', text: 'Subscription', value: 'monthly', setting: () => state.period }),
MultiButton({ onclick: () => state.period = 'yearly', text: 'Yearly', value: 'yearly', setting: () => state.period }),
) |
Beta Was this translation helpful? Give feedback.
For the derived state to be reactive to the field updates of the reactive object, you need to "access" the field inside the binding function, instead of accessing the field outside the binding function and pass-in the result into the binding function (see the caveat here).
For your example to work, you need to change the value of
setting
property into a function and invoke the function inside the binding function ofvan.derive
. That is, the code can be changed into the following:btw: another thing needs to fix is to change
highlight
intohighlight.val
for accessing the value of the state.