5

As the title,
I want to set checkbox "checked" by default when the page was fully load,
but in the tutorial about Material-UI Checkbox component, didn't have the defaultChecked props.
When I add checked={true} props, then get arror like
"A component is changing an uncontrolled input of type checkbox to be controlled...etc"
How should I do?

there is my code
I want to list all the group, include the default group and the other let the user to choose multi group.

  export default class AcceptButton extends Component {
  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    this.state = {open: true}
  }
  handleChange = event => {
    this.setState({checked: event.target.checked})
  }
  render() {
    return (
      <Fragment>
       <div>
         group : 
       </div>
       <div className="f-col">
       {
        group.data.map(g => {
          if (data.filter(d => d.gid == g.gid).length != 0) {
            return (
              <FormControlLabel
                key={g.gid}
                control={
                  <Checkbox
                    disabled={true}
                    onChange = {this.handleChange}
                    color="primary"
                    checked={this.state.open}
                  />
                }
                label={g.gname}
              />
          )}
          else {
            return (
              <FormControlLabel
                key={g.gid}
                control={
                  <Checkbox
                    onChange={this.handleChange}
                    value={g.gname}
                    color="primary"
                  />
                }
                label={g.gname}
              />
          )}
        })
      }
    </div> 
    <button className="btn" onClick={this.postassignhandle}>update</button>
  </Fragment>
)

6 Answers 6

12

it does have a defaultChecked props and you can use it like :

<Checkbox defaultChecked={true} 
          onChange={this.handleChange}
          color="primary"
 />
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this but then React gives me a warning: Warning: ForwardRef(SwitchBase) contains an input of type checkbox with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props.
@TommiL. yeah right , probably when you use defaultChecked prop ,checked prop is not necessarily to use and using defaultChecked and checked props at same time has a Intervening for React to manage the checkbox , so you should remove one of them , Thank you for your comment
I wonder why this prop doesn't appear on the Checkbox documentation.
Using defaultChecked instead of passing a value to checked results in error: MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized.
1

Made checkboxstate a maps type

const checkboxstatemap = new Map()
export default class AcceptButton extends Component {
constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)

    this.state = {checkboxstate: group.data.map((item) =>  checkboxstatemap.set(item.gid, true ))}
}

componentDidMount() {
handleChange = event => {
    this.setState({checked: event.target.checked})
}
render() {
    return (
    <Fragment>
    <div>
        group : 
    </div>
    <div className="f-col">
    {
        group.data.map(g => {
        if (data.filter(d => d.gid == g.gid).length != 0) {
            return (
            <FormControlLabel
                key={g.gid}
                control={
                <Checkbox
                    disabled={true}
                    onChange = {this.handleChange}
                    color="primary"
                    checked={this.state.checkboxstate.get(g.gid)}
                />
                }
                label={g.gname}
            />
        )}
        else {
            return (
            <FormControlLabel
                key={g.gid}
                control={
                <Checkbox
                    onChange={this.handleChange}
                    value={g.gname}
                    color="primary"
                />
                }
                label={g.gname}
            />
        )}
        })
    }
    </div> 
    <button className="btn" onClick={this.postassignhandle}>update</button>
</Fragment>
)

3 Comments

But I can't know how many checkbox should have. So set state to all checkbox can't work I think.
@honeytoast is your gid field sequential ?
No, it doesn't.
1
import React from 'react';
import Checkbox from '@material-ui/core/Checkbox';

class Checkboxes extends React.Component {
  state = {
    checkedBox: true,
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.checked });
  };

  render() {
    return (
      <div>
        <Checkbox
          checked={this.state.checkedBox}
          onChange={this.handleChange('checkedBox')}
          value="checkedBox"
        />
      </div>
    );
  }
}

Try this.

Comments

1
import React, { useCallback, useState } from 'react';
import { Checkbox, FormControlLabel } from '@material-ui/core';

const defaultProps = {
    margin: 'normal',
    onChange: (e) => {}
};
const InputCheckbox = (props) => {
    const { onChange, label, value=false, name, checkedIcon, icon, className, style } = props;

    const [ isChecked, setChecked ] = useState(value);
    const _onChange = useCallback(
        (e) => {
            setChecked((value) => {
                onChange(e, { [e.target.name]: !value });
                return !value;
            });
        },
        [ onChange ]
    );
    return <FormControlLabel className={className} style={style} label={label} control={<Checkbox name={name} icon={icon} checkedIcon={checkedIcon} checked={isChecked} onChange={_onChange} />} />;
};
InputCheckbox.defaultProps = defaultProps;
export default InputCheckbox;

use onChange to callback value and use value to do initialize

Comments

0

youst must add attribute checked inc component, sometimes use value but don`t work always use checked attribute.

<Checkbox onChange={this.handleChange}
          color="primary"
          checked={this.state.checked}
 />

3 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
sometimes use value but don`t work always use checked attribute can you explain ?
yeah, use checked is de functional mode then value don't work
0

"When I add checked={true} props, then get error like" In react you cant add constant values like checked={true} you have use state variables so it will help react rendering process. ex:-

const [checked,setChecked] = useState(false);

<Checkbox ...
          checked={checked}
 />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.