Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Programmatically toggle Switch #6375

Closed
guygit opened this issue May 13, 2024 · 4 comments
Closed

Programmatically toggle Switch #6375

guygit opened this issue May 13, 2024 · 4 comments

Comments

@guygit
Copy link

guygit commented May 13, 2024

Provide a general summary of the issue here

The docs do not mention the use case how to programmatically trigger the Switch.
Since you are exposing an inputRef property, I assumed I could do it like so:

`
useEffect(() => {
ref.current.checked = true;
}, [update]

..
`

However that doesn't work.

🤔 Expected Behavior?

Switch should toggle

😯 Current Behavior

Switch doesn't toggle

💁 Possible Solution

No response

🔦 Context

No response

🖥️ Steps to Reproduce

`
useEffect(() => {
ref.current.checked = true;
}, [update]

..
`

Version

latest

What browsers are you seeing the problem on?

Chrome

If other, please specify.

No response

What operating system are you using?

mac

🧢 Your Company/Team

No response

🕷 Tracking Issue

No response

@reidbarber
Copy link
Member

You should use a controlled value for this use case, and update the value programmatically.

The visually hidden input is dependent on the state of the Switch component, which wouldn't get updated in that case.

@guygit
Copy link
Author

guygit commented May 13, 2024

Thx for the feedback.

I already tried that as well, but I cannot observe that the Switch is actually moving.
const [value, setValue] = useState('low'); useEffect(() => { setTimeout(() => { setValue('high'); }, 2000); }, []); <Switch name="power" value={value}> Lo bro </Switch>

@reidbarber
Copy link
Member

Try passing isSelected={selected}, where selected is a boolean. The value attribute is used for the form element value.

@guygit
Copy link
Author

guygit commented May 13, 2024

Reid - fantastic! (I was thinking "isSelected" was a read-only prop)

Thank you very much!

@guygit guygit closed this as completed May 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants