Control inputs React

Asked

Viewed 30 times

1

I have a component that renders a Material-ui Switch-style checkbox. The code is this:

import styles from './styles.module.scss';
import { useState } from 'react';
import { handleInputsRelativeIds } from '../../utils';
import utilStyles from '../../../styles/utilStyles.module.scss';
import Switch from '@material-ui/core/Switch';

export default function Checkbox({ head, text, children, checked }) {

    const [check, setCheck] = useState(checked)


    if (children) {

        handleInputsRelativeIds()
    }

    return (
        <div className={styles.field} data-children={children}>
            <div className={styles.check_wrap}>
                <div className={styles.text}>
                    {
                        head ? (
                            <h3 className={utilStyles.headingXL}>{ head }</h3>
                        ) : (
                            <></>
                        )
                    }
                    <p>{ text }</p>
                </div>
                <Switch color="primary" onClick={() => { setCheck(!check)}} defaultChecked={check}  />
            </div>
        </div>
    )
}

The problem is that it returns an error when changing the input state.

Material-UI: A Component is Changing the default checked state of an uncontrolled Switchbase after being initialized. To Suppress this Warning opt to use a Controlled Switchbase.

It seems the problem is that the component is not being controlled with React State. But I am using the state check . How can I solve this error with functional components?

1 answer

3


if you observe the switch documentation of the ui.

It is very clear how to make this transition from checked.

  return (
    <Switch
      checked={checked}
      onChange={(e) => { setChecked(e.target.checked) }}
      color="primary"
    />
  )
  • Add an onChange and not an onClick

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.