I have a table of data, and it has checkbox field which allows people to check or uncheck it.
If i click the unchecked checkbox, it will send to database to make status of that checklist to be true, as if i click the checked checkbox, it will send to database to make status of that checklist to be false. I have made it and do the change status in database.
this is the JSON data if i click the unchecked checkbox, from this
data={"Id":"123", "checklist": false}
to this
data={"Id":"123", "checklist": true}
The problem is when i click it it doesn't change the checkbox to be checked in interface, i need to reload page to make it checked
This is my code snippet:
class Apps extends React.Component {
constructor (props) {
super(props);
this.state = {
blablabla:"ex"
}
this.onCheckChange=this.onCheckChange.bind(this)
}
onCheckChange(e){
console.log(e.target.checked)
this.setState({
[e.target.name]:e.target.checked
})
}
onSubmitChecklistClicked = async (Id) => {
var response = await RequestHandler(`${ENVIRONMENT.API_URL}api/v1.0/checklist`, {}, {Id})
console.log(response);
}
render () {
return(
<Input type="checkbox" className="input-checked"
checked={data.checklist}
onChange={this.onCheckChange,() => this.onSubmitChecklistClicked(data.Id)}></Input>
)
}
}
for the first time, the checklist is checked or unchecked is based the JSON given by database, I dont know which one is my problem, at the onCheckChange function or checked{} attribute, or onChange{} attribute.
In order for the checklist to change you have to set the checked
prop to a variable in your state. This way, when you do setState
the component will render again and this time checked
prop of the input would be set to false.
Example code would be such
class Apps extends React.Component {
constructor (props) {
super(props);
this.state = {
isChecked: false, // or true depending on what you want
...
}
this.onCheckChange=this.onCheckChange.bind(this)
}
onCheckChange(e){
console.log(e.target.checked)
this.setState({
isChecked: e.target.checked // set the variable in the state
})
}
onSubmitChecklistClicked = async (Id) => {
var response = await RequestHandler(`${ENVIRONMENT.API_URL}api/v1.0/checklist`, {}, {Id})
console.log(response);
}
render () {
return(
<Input type="checkbox" className="input-checked"
checked={this.state.isChecked} // use it here
onChange={this.onCheckChange,() => this.onSubmitChecklistClicked(data.Id)}></Input>
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.