2

I'm writing a page that converts temperature from Celcius to Fahrenheit.

User gives temperature in celcius in the first input field, then onChange should call function convertCelciustoFahr.

The convertCelciustoFahr changes the state.fahrenheit by function this.setState() and temperature in fahrenheit should update to the second input field.

class App extends Component {

constructor(props){
  super(props);
  this.state = {
    //Temperature in fahrenheit
    fahrenheit: 0,
    //Temperature in celcius
    celcius: 0,
  };
  //Binding
  this.convertCelciustoFahr = this.convertCelciustoFahr.this;
}


//Converts celcius to fahrenheit
convertCelciustoFahr(event){
  var celcius = Number(event.target.value);
  this.setState( function(state,props){
    return{
      fahrenheit: (celcius-32)/(5/9),
    } 
  }
  )
}

render() {
  return (
    <div className="App">

    <h1>Celcius to Fahrenheit converter</h1>
    <form id="conversion">
      <input className="Celcius" placeholder="°C" onChange={this.convertCelciustoFahr} />
      <p>=</p>
      <input className="Fahrenheit" value={this.state.fahrenheit} placeholder="°F" />

    </form>
  </div>
  );
}
}


export default App;

Here is the html:

<body>
<noscript>
  You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div data-reactroot="" class="App">
  <h1>Celcius to Fahrenheit     converter</h1>
  <form id="conversion">
    <input class="Celcius" placeholder="°C">
    <p>=</p>
    <input class="Fahrenheit" value="0" placeholder="°F">
  </form>
</div>
</div>

It seems that Javascript is not enabled and the onChange event is not triggered.

Why onChange not updating value to the fahrenheit input field?

1 Answers1

2

bind using

 this.convertCelciustoFahr = this.convertCelciustoFahr.bind(this);
Vikram Saini
  • 2,713
  • 1
  • 16
  • 33
  • -1 because "*You can use arrow function as it automatically binds to this*" is wrong. Arrow functions don't "bind" as they don't have a `this`. – Chris Jul 03 '17 at 14:56
  • 1
    hi @Chris yes you are right i did not explain it right so i updated my answer:) it should have been arrow fucntions are bound to the lexical this of their current context – Vikram Saini Jul 03 '17 at 14:59