My checkbox is not ticking/unchecking

Asked

Viewed 154 times

0

I’m implementing some checkbox with React, I can settar to initially be checked or not, but I can’t change that state.

How to solve?

My Main Class

class NewsletterConfig extends Component {
constructor(props) {
    super(props)
    this.state = {
        promocoes: true,
    }

    this.handleClick = this.handleClick.bind(this)
}

handleClick({ target }) {
    this.setState({
        [target.name]: !target.checked,
    })
}

render() {
    return (
        <div>
            <Componente01
                name="promocoes"
                title="Tab"
                checked={this.state.promocoes}
                handleClick={this.handleClick}
            />

The Componente01

const NewsletterCalling = ({
title,
name,
checked,
 }) => (
<div>
    <label htmlFor={name}>{title}</label>
    <Checkbox name={name} checked={checked} />
</div>
)

NewsletterCalling.propTypes = {
title: string.isRequired,
name: string.isRequired,
checked: bool.isRequired,
handleClick: func.isRequired,
}

And the Checkbox

const Checkbox = ({ name, checked, handleClick }) => (
<div>
    <input
        id={name}
        name={name}
        checked={checked}
        type="checkbox"
        onClick={handleClick}
    />
    <span />
</div>
)

Checkbox.propTypes = {
    name: string.isRequired,
    checked: bool.isRequired,
    handleClick: func.isRequired,
}

1 answer

0


In the handleClick method, you do not need to invert the target.checked value because this value already comes with the right value ("inverted") when clicking the checkbox. Thus, you just need to remove the exclamation mark "!":

handleClick({ target }) {
    this.setState({
        [target.name]: target.checked,
    })
}

You can check this by logging the value (console.log(target.checked)) before calling the setState method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.