My checkboxes are not ticking / unchecking

0

I'm implementing some checkbox with React, I can set it to initially be checked or not, but I can not change that state.

How to solve?

My PrincipaL 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 Component01

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,
}
    
asked by anonymous 16.08.2018 / 17:51

1 answer

0

In the handleClick method, you do not need to invert the value of target.checked because this value already comes with the right value ("inverted") when clicking on the checkbox. So, 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.

    
26.08.2018 / 15:15