1

I have react component like this:

import React, { Component } from 'react'
import { Sidebar, Segment, Button, Menu, Image, Icon, Header } from 'semantic-ui-react'

export default class Footer extends Component {

    constructor(props) {
        super(props)
        this.state = {
            visible: false
        }
        this.handleClick = this.handleClick.bind(this);
        this.handleClick();
    }


    handleClick() {

        this.props.socket.on('connect', function () {
            console.log("PRINT this.state.visible");
            console.log('Connected');
        });

        this.props.socket.on('disconnect', function () {
            console.log('Disconnected');
        });
    }

    render() {
        return (
            <div className='create-task-section'>
                "HELLO"
            </div>
        )
    }
}

I am using websocket io. In method this.props.socket.on I want print

this.state = { visible: false }

But when I print this variable, I am getting undifined error. How can I read/change/update this.state values in anonymous method likethis.props.socket.on?

Thank you for your help!

  • You must not `bind` the `handleClick` method but the anonymous function. – Bergi Jul 29 '17 at 22:51
  • I assume you meant `console.log("PRINT", this.state.visible)` not `console.log("PRINT this.state.visible")`? – Bergi Jul 29 '17 at 22:52

1 Answers1

2

bind 'this'.

this.props.socket.on('connect', function () {
            console.log("PRINT this.state.visible");
            console.log('Connected');
        }.bind(this));

to change state variable use 'this.setState({visible: false})' never mutate state with this.state.visible as that wont work. Also event handling should be done in componentDidMount method, not on handleClick as it will not work till user clicks.

Shishir Arora
  • 5,521
  • 4
  • 30
  • 35
  • why do you bind `this` to function instead of using es6 arrow function? – Maxim Kuzmin Jul 29 '17 at 21:47
  • @MaximKuzmin there are many ways to bind 'this'. Arrow functions are also good. Initializing a bound function in the constructor is also good. using es7 "::" for bound is also there. using react instance method is also good. – Shishir Arora Jul 29 '17 at 22:07