Reputation: 31
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 :)
Upvotes: 3
Views: 35535
Reputation: 388
The TypeError: Cannot read properties of null (reading 'checked')
comes because when you first render, your checkbox with that id isn't mounted to the DOM yet. Because of that the document.getElementById("myCheck")
returns null.
Most of the time with React you shouldn't use the document object's functions.
You should instead use React's state. Since you're using a class component, you can use this.state to have a property the value of which tells whether the checkbox is checked or not. The checkbox needs a change handler, something like
<input type="checkbox" id="myCheck" onChange={(state) => this.setState({isChecked: !state.isChecked})} />
Then in getClassBadge
, simply check for the state:
return this.state.isChecked
? "badge m-2 bg-warning"
: "badge m-2 bg-primnary"
Upvotes: 4