adammo
adammo

Reputation: 211

Executing function on click gives errors

I wanted my code to execute if function when I click the button, however no matter what I try it either does nothing or throws error at me. Does anyone have some clue what could be wrong here?

import React from 'react';
export default class MojaKlasa extends React.Component {
  state = {showPass: 0};

  render() {
    function MojaFunkcja() {
      if (this.state.showPass === 0) {
        this.setState([showPass: 1])
      } else {
        this.setState([showPass: 0])
      }
    };
    return (
      <button className="przycisk" onClick={() => MojaFunkcja()}></button>
      <p>{this.state.showPass}</p>
    );
  };
}

Upvotes: 0

Views: 56

Answers (4)

duc mai
duc mai

Reputation: 1422

I suggest to change showPass from int to boolean then your life will be easier

import React from 'react';
export default class MojaKlasa extends React.Component {
  state = {
    showPass: false
  };
  render() {
    function MojaFunkcja() {
     this.setState({ showPass: !this.state.showPass })
    };
    return (
        <>
      <button className="przycisk" onClick={MojaFunkcja}></button>
      <p> {this.state.showPass}</p>
        </>
    );
  };
}

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

this.setState([showPass: 0]) is not valid JavaScript syntax. You have to use {} instead of [] to create an object literal:

this.setState({showPass: 0})

Same for the other setState call.

You also cannot two elements after each other like this return (<button></button> <a />);. You either have to return an array of elements, or a single element:

return [ // <- array literal
   <button />
   <a />
];

// or

return (
  <span> // <- parent node
    <button />
    <a />
  </span>
);

Upvotes: 0

V&#237;tor Fran&#231;a
V&#237;tor Fran&#231;a

Reputation: 767

You can make something like this:

export default class App extends React.Component {
  state = { showPass: 0 };

  MojaFunkcja = () => {
    this.setState({ showPass: (this.state.showPass === 1) ? 0 : 1 });
  };

  render() {
    return (
      <div>
        <button className="przycisk" onClick={this.MojaFunkcja} />
        <p>{this.state.showPass}</p>
      </div>
    );
  }
}

Upvotes: 2

SakoBu
SakoBu

Reputation: 4011

Quite a few syntax errors and issues in your code...

import React from 'react';

export default class App extends React.Component {
  state = { showPass: 0 };

  MojaFunkcja = () => {
    this.setState({ showPass: this.state.showPass + 1 });
  };

  render() {
    return (
      <div>
        <button className="przycisk" onClick={this.MojaFunkcja} />
        <p>{this.state.showPass}</p>
      </div>
    );
  }
}

Upvotes: 1

Related Questions