N
N
Ninja Mate2016-02-16 17:37:10
JavaScript
Ninja Mate, 2016-02-16 17:37:10

Why doesn't setState work in this case?

I can't get the change function to change state open:

export class UserFirstForm extends Component {

    constructor(...args) {
        super(...args);
        this.state = {
            open: false,
            value: 'select'
        };
    }

    change(){
        console.log("WTF");
        this.in.state({ open: !this.state.open })
    }

    render() {
return (
            <div>

                <form>

                    <Input type="select" value={this.state.value} label="Please select who the Activity is in relation to:" placeholder="Select"
                           onChange={this.change}>
                        <option value="Patient">Patient</option>
                        <option value="Escort">Escort</option>
                        <option value="Carer">Carer</option>
                        <option value="Family">Family Member</option>
                        <option value="Other" >Other</option>
                    </Input>


                    <Button onClick={()=> this.setState({ open: !this.state.open })}>
                        click
                    </Button>

                    <Collapse in={this.state.open} ref="myCol">
                        <div>
                            <Well>
                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad 
                            </Well>
                        </div>
                    </Collapse>

while this.setState({ open: !this.state.open })}> works and everything goes into change()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2016-02-16
@victorzadorozhnyy

You simply lose the pointer to this:
Try to autobind:

change = () => {
        console.log("WTF");
        this.setState({ open: !this.state.open })
    };

Or bind it in the constructor (equivalent to the method above, but it's not convenient)
constructor(...args) {
        super(...args);
        this.state = {
            open: false,
            value: 'select'
        };
        this.change = this.change.bind(this)
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question