I am trying to have a checkbox that change a className of another tag dynamically. There is my code :
import "bootstrap/dist/css/bootstrap.min.css";
class Task extends Component {
state = {
task: "DevApp",
};
isChecked = () => {
console.log("True");
return true;
};
render() {
return (
<React.Fragment>
<span className="bg-warning">{this.state.task}</span>
<label>
<input type="checkbox" id="myCheck" />
</label>
<span className={this.getClassBadge()}>Done</span>]
</React.Fragment>
);
}
getClassBadge() {
var x = document.getElementById("myCheck").checked;
if (x) {
return "badge m-2 bg-warning";
} else {
return "badge m-2 bg-primnary";
}
}
}
export default Task;
And i get TypeError: Cannot read properties of null (reading 'checked')
I've tried this way :
render() {
return (
<React.Fragment>
<span className="bg-warning">{this.state.task}</span>
<label>
<input type="checkbox" id="myCheck" />
</label>
<span className={this.getClassBadge()}>Done</span>]
</React.Fragment>
<script>
getClassBadge() {
var x = document.getElementById("myCheck").checked;
if (x) {
return "badge m-2 bg-warning";
} else {
return "badge m-2 bg-primnary";
}
}
</script>
);
}
but everything is underlined in red. I would like to have a checkbox and if the checkbox is checked the next span's className will change to have a cool effect. Can someone please help me? I am sorry if it is very basic but i am only starting out :)
Aucun commentaire:
Enregistrer un commentaire