#checkbox controlled from outside

28 messages · Page 1 of 1 (latest)

rotund pewter
#

I want to control a checkbox from the outside and expose either a function onChange and the props.checked that will be reactive.

import { createSignal } from 'solid-js';
import c from './Switch.module.scss';
function SwitchButton(props) {
return (
<div
style={{
display: 'flex',
}}
>
<div style={{ 'align-self': 'center' }}>{props.label1}</div>
<label class={c.switch}>
<input
type={'checkbox'}
class={c.input}
checked={props.checked}
onChange={(e) => props?.onChange?.(e)}
/>
<span class={c.slider}></span>
</label>
<div style={{ 'align-self': 'center' }}>{props.label2}</div>
</div>
);
}

export default SwitchButton;

twilit zinc
#

The code looks OK. In the parent component, which controls the checkbox, a signal could control it like this:

const [isChecked, setChecked] = createSignal(false);

<SwitchButton checked={isChecked()} onChange={() => setChecked((checked) => !checked)} />
#

If the question is how to expose either checked or set function, I don't think you can do that - you need to have both.

rotund pewter
#

props.checked is not reactive when I use it like that and i change it with another button

#

it's strange

#

i think maybe has to do someting with the styles

twilit zinc
#

It doesn't have to do anything with styles, that's certain. The reactivity is broken, but since you did not destructure, I don't see an obvious reason.

rotund pewter
twilit zinc
#

And what's wrong with that component?

#

Ah, you are missing onChange={(e) => props?.onChange?.(e.currentTarget.checked)}

#

TypeScript would catch the error

rotund pewter
#

do you know how to put the classes with that playground

twilit zinc
#

classes?

#

Solid is pretty much agnostic about CSS, if that's what you mean.

#

You can use whatever you like, provided that it's not framework specific.

rotund pewter
#

with the playground page i mean haha

twilit zinc
#

you should be able to use plain css

#

Not sure about modules

rotund pewter
#

but in the playground i send before i used plain css and it seems it don't work correctly

twilit zinc
#

There's probably an error in the CSS or the way how it's applied.

#

It's a playground, not meant to be used as a dev tool.

rotund pewter
#

@twilit zinc I see.. thanks

twilit zinc
#

Don't mention it. If you need help with setting up CSS, Solid is quite agnostic there, but you can use pretty much anything non-framework specific.

rotund pewter
#

I solved 😄

#

the checked property of the input that is part of the switch was interfering somehow with the reactivity of the singal passed by props

twilit zinc
#

Good to know. Haven't seen any issues with your examples.