Switch initially checked
See original GitHub issueGiven the following truncated example, I would expect the switch to be initially turned on:
import { Switch } from 'formik-material-ui';
initialValues = { myField: true }
<FormControlLabel
control={<Field name="myField" type="checkbox" component={Switch} />}
label="My Field"
/>
I noticed issue #41 and PR #42 but couldn’t get it to work out of the box.
I added some logs to the Switch
component, and noticed that field.value === undefined
. So I added value={values.myField}
as a prop to the Field
, and it works now. Not sure if this is how it’s supposed to work.
Working version:
<Formik render={({ values }) =>
<form>
<FormControlLabel
control={<Field name="myField" value={values.myField} type="checkbox" component={Switch} />}
label="My Field"
/>
</form>
</Formik>
versions:
@material-ui/core@3.9.3
formik-material-ui@0.0.16
react@16.8.6
Issue Analytics
- State:
- Created 4 years ago
- Comments:6
Top Results From Across the Web
how to set <Switch/> with initial 'checked'
I expect the the uncontrolled component Switch which is set to 'checked' by default, i don't how to define the variable with useRef?...
Read more >How can I check if the switch is on or off - HTML & CSS
By checking if it's on or off i can, as a first step, print “status: 1” or “status: 0”.
Read more >Switch Component: Checkbox
With NVDA 2020.4: announces "checkbox" role and initial state. Activating the 'switch' will announce the new state ("checked" or "not checked").
Read more >ARIA: switch role - Accessibility - MDN Web Docs - Mozilla
The switch is implemented as a <button> element which is initially checked courtesy of its aria-checked attribute being set to "true" .
Read more >Building a switch component - web.dev
A switch functions similar to a checkbox but explicitly represents boolean on and off states. This demo uses <input type="checkbox" role="switch ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Oh god, it’s the
type="checkbox"
. Just confirmed it in your sandbox.You can access setFieldValue and values from render props.
<Switch checked={values.offer} onChange={(e) => { setFieldValue( 'offer', e.target.checked, false ) }} color="primary" name="offer" inputProps={{ 'aria-label': 'offer status' }} />
Whenever you need to modify the values check to see the available helper functions. Most of the use cases will be ready to use. If you couldn’t find any way, then create your own.