Amias Burrows
Amias Burrows

Reputation: 11

How to update state in React

I've been trying for a while to get this to work and any method I've come across doesn't seem to work. I've tried W3 Schools and this Stack Overflow question and any others seem to follow the same format. I can't seem to see whats wrong with my code. If anyone can find the issue that would really help:

import React from 'react';

export class Hamburger extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            click: false
        };
    }

    handleClick = () => {
        if (this.state.click) {
            this.setState({click: false});
        } else {
            this.setState({click: true});
        };
    }
    render() {
        let className = 'hamburger';
        if (this.state.click) {
            className += ' cross';
        }

        return (
            <div
                className={className}
                onclick={this.handleClick}
            >
                <svg
                    viewbox='0 0 100 100'
                    preserveAspectRatio='xMidYMid meet'
                >
                    <line x1='10' x2='90' y1='20' y2='20' id='top'/>
                    <line x1='10' x2='90' y1='50' y2='50' id='mid'/>
                    <line x1='10' x2='90' y1='80' y2='80' id='btm'/>
                </svg>
            </div>
        );
    }
}

Thanks in advance

Upvotes: 0

Views: 195

Answers (4)

Dawood Ahmad
Dawood Ahmad

Reputation: 474

try this one:

 import React from 'react';

export class Hamburger extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            click: false
        };
    }

    handleClick = () => {
        this.setState({click: !click});
    }
    render() {
        let className = 'hamburger';
        if (this.state.click) {
            className += ' cross';
        }

        return (
            <div
                className={className}
                onclick={this.handleClick}
            >
                <svg
                    viewbox='0 0 100 100'
                    preserveAspectRatio='xMidYMid meet'
                >
                    <line x1='10' x2='90' y1='20' y2='20' id='top'/>
                    <line x1='10' x2='90' y1='50' y2='50' id='mid'/>
                    <line x1='10' x2='90' y1='80' y2='80' id='btm'/>
                </svg>
            </div>
        );
    }
}

Upvotes: 0

Anil Singha
Anil Singha

Reputation: 428

Change your onclick to onClick event handlers always in camelCase

Upvotes: 1

Senthilkumar Alagar
Senthilkumar Alagar

Reputation: 9

Event handlers should be in camel cases. I can see you have defined as onclick instead of onClick.

Change to <div className={className} onClick={this.handleClick} >

Upvotes: 1

Mehdi Hassan Akash
Mehdi Hassan Akash

Reputation: 56

your onclick should be onClick

Upvotes: 1

Related Questions