proton
proton

Reputation: 81

How to submit defaultValue if there is no user-given value React

So I have this checkbox in a form in my React application that sets the defaultChecked value to an object's "static value"

<input type='checkbox' name='static' defaultChecked={obj.static}/>

Now whenever I submit the form, it doesn't read from the defaultChecked, and I have to change it, for it to even read from the checkbox.

Is there any way to fix this? Thanks.

Upvotes: 0

Views: 30

Answers (1)

xuscrus
xuscrus

Reputation: 117

defaultChecked is not recommend to use.

I will try to store that info in state like:

https://codesandbox.io/s/holy-snow-l3u6b

const obj = {
  defaultValue: true
};

class Test extends React.Component {
  constructor() {
    super();
    this.state = {
      checked: obj.defaultValue
    };

    this.onStaticChangeHandler = e => {
      this.setState({
        checked: e.target.checked
      });
    };
  }

  render() {
    return (
      <input
        type="checkbox"
        name="static"
        onChange={this.onStaticChangeHandler}
        checked={this.state.checked}
      />
    );
  }
}

Upvotes: 2

Related Questions