checkbox controlled from outside
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;
19 Replies
The code looks OK. In the parent component, which controls the checkbox, a signal could control it like this:
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.
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
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.
A bare minimal example
https://playground.solidjs.com/anonymous/1483e120-9301-4ff1-a35d-e39d612e079c
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
there's the whole component ( itried to import css but somewhat don't get correctly that import)
https://playground.solidjs.com/anonymous/82507011-d034-48f7-82b2-a154f2ff9e93
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
And what's wrong with that component?
Ah, you are missing onChange={(e) => props?.onChange?.(e.currentTarget.checked)}
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
TypeScript would catch the error
do you know how to put the classes with that playground
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.
with the playground page i mean haha
you should be able to use plain css
Not sure about modules
but in the playground i send before i used plain css and it seems it don't work correctly
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.
@.high1 I see.. thanks
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.
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
Good to know. Haven't seen any issues with your examples.
Hey guys, I noticed that checkbox can't be controlled. For instance, if I pass
<Switch checked={false} onChange={console.log} />
I still will be able to change checked state. How to deal with this?