Reputation: 21
I'm learning ReactJS and today I can't resolve a difficulty, so I need your help.
I want to make a "Remember Me" for users that want to stay connected after reopening the website.
This is my code :
My function :
handleChangeCheckBox = (event) => {
console.log(event.target.checked)
this.setState({
isChecked: event.target.checked
})
}
When I call the function in the input checkbox field with an onChange :
<p>
<Input
type="checkbox"
name="rememberCheckbox"
className="rememberCheckbox"
id={this.state.isChecked}
onChange={this.handleChangeCheckBox}
/>
Remember Me
</p>
Nothing appears in my console when I click on the checkbox, so it seems like the calling function isn't working.
Upvotes: 2
Views: 14145
Reputation: 1
handleChangeCheckBox = () => { this.setState({ isChecked: ! this.state.isChecked }) }
Upvotes: 0
Reputation: 826
it could be triggering twice.
if you are using create-react-app
then your App
component is wrapped in StrictMode
like this:
<React.StrictMode>
<App />
</React.StrictMode>,
go to index.js
and remove <React.StrictMode></React.StrictMode>
https://github.com/facebook/react/issues/12856#issuecomment-390206425
Upvotes: 0
Reputation: 69
please try this. replace value
with checked
<input type="checkbox"
name="rememberCheckbox"
checked={this.state.isChecked}
onChange={this.handleCheckBox}
/>
Upvotes: 6
Reputation: 953
Code tested at given url enter link description here
class App extends Component {
constructor(props) {
super(props);
this.state = { isChecked: false };
}
handleCheckBox = event => {
console.log(event.target.checked);
this.setState({
isChecked: event.target.checked
});
};
render() {
return (
<div>
<p>
<input
type="checkbox"
name="rememberCheckbox"
value={this.state.isChecked}
onChange={this.handleCheckBox}
/>
Remember Me
</p>
</div>
);
}
}
Upvotes: 1
Reputation: 3682
Welcome to Stack overflow!
Based on the code you shared, your function should be getting executed. I suspect you have an error somewhere else in your class rather than in those two code snippets you shared.
You can check this simple sandbox I made with a very barebones implementation like the one you have: https://codesandbox.io/s/react-simple-check-box-7etp4
One thing you're missing is using the checked
html attribute rather than id
. That's what will tell the checbox whether it's checked or not. It replaces the value
attribute you use for input fields.
You also seem to be using an Input
component. Try changing it for a normal HTML input
instead.
Upvotes: 0