Why buttons are not working on this Simple React App

Syntax issue:

this.setState = ({
      result: nombreBoton
    })

setState is a function, should be this.setState({ result: nombreBoton }).

It should work fine after fixing that


Also delete this line:

this.botonPresionado = this.botonPresionado.bind(this);

You are using a class property (botonPresionado = nombreBoton => {), you only need to bind if you are using a class method (if it was botonPresionado(nombreBoton) { instead).

Your class property is an arrow function, which has no this, so you cannot (and do not need to) bind this to it.

Example:


EDIT, also, you don’t need the constructor, you can just write:

class App extends React.Component {
  state = {
    result: ""
  };

  botonPresionado = nombreBoton => {
    this.setState({
      result: nombreBoton
    });
  };

  render() {
    .....

EDIT 2: if you want to go nuts and try newer features, this is functionally identical:

const App = () => {
  const [result, setResult] = React.useState("");

  return (
    <div className="App">
      <Display result={result} />
      <Keypad botonPresionado={setResult} />
    </div>
  );
};

const Display = ({ result }) => <p id="display">{result}</p>;

const Keypad = ({ botonPresionado }) => (
  <div id="grid2">
    <button onClick={e => botonPresionado(e.target.name)} id="clear" name="clear">AC</button>
    <button id="divide" name="divide">/</button>
    <button id="multiply" name="multiply">*</button>
    <button id="seven" name="seven">7</button>
    {/* rest of your buttons here */}
  </div>
);
1 Like