How to pass props to the state in React

Asked

Viewed 262 times

0

Good afternoon. I’m developing a calculator app with React. I would like to know how to pass the value of a property from one of my buttons to the state value.

For example: button 7, pass its value 7 to this.state.result.

import React,{Component} from 'react';
import './App.css';

class App extends Component {
  constructor(){
    super();
    this.state = {
      result: 0,
      number: 0      
    }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(){
    this.setState({
      result: this.props.value
    })
  }

  render(){
    return (
      <div className="App">
        <button className="result">{this.state.result}</button>
        <button value="0">AC</button>
        <button>+/-</button>
        <button>%</button>
        <button className="opBut">/</button>
        <button value="7" onClick={this.handleClick}>7</button>
        <button value="8">8</button>
        <button value="9">9</button>
        <button className="opBut">X</button>
        <button value="4">4</button>
        <button value="5">5</button>
        <button value="6">6</button>
        <button className="opBut">-</button>
        <button value="1">1</button>
        <button value="2">2</button>
        <button value="3">3</button>
        <button className="opBut">+</button>
        <button value="0" className="button0">0</button>
        <button>.</button>
        <button className="opBut">=</button>
      </div>
    );
  }
}

export default App;
  • Format your code so we can understand and where is the button in the render?

2 answers

2


If the idea is to read the attribute value Just use the button event.target.value:

handleClick(){
  const valBotaoClicado = event.target.value;
  this.setState({
    result: valBotaoClicado
  })
}

1

You don’t necessarily need to declare a function to update a state.

For example, a data entry can be updated as soon as there is any change using the onChange():

<input value={this.state.value}  onChange={(value) => this.setState({valor: value})} />

And if you want to work with some action of these states you can create a function (doing the Bind of course) that work with the values you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.