Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React input text default value and onblur function make input text read only

guys, I am working on react js

I have created an input text and on blur of that input button I am calling a method and updating the state variable

but seem like if I use on blur instead of onChange then input text become read only field

<!DOCTYPE html>
<html>

  <head>
    <script data-require="react@*" data-semver="0.13.3" src="http://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
    <script data-require="react-jsx@*" data-semver="0.13.1" src="http://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>

    <link rel="stylesheet" href="style.css" />
    <script type="text/jsx">

      var App = React.createClass({
          getInitialState: function () {
              return {value: 'Hello!'};
          },

          changeTo: function (e) {
              this.setState({value: e.target.value});
          },

          render: function () {
              return (
                  <div>{this.state.value}
                      <input type="text" defaultValue={this.state.value || ''} 
                         value={this.state.value} onBlur={(e) => this.changeTo(e)} />
                  </div>
              );
          }
      });

      React.render(
          <App />,
          document.getElementById('app')
      );
    </script>
  </head>

  <body>
    <div id="app"></div>
  </body>

</html>
like image 372
Ratan Paul Avatar asked Sep 06 '25 03:09

Ratan Paul


1 Answers

You need to add onChange listener otherwise it will not work.

Reason: When you specify value={this.state.value} it means you are binding input text value to the variable value and react takes over the control for updating value in input box. By adding onChange listener, you tell react to call a component function to update value which basically updates the state of the component forcing it to call render function and updating the value in input text.

      changeTo: function (e) {
          this.setState({value: e.target.value});
      },

      updateValue: function (e) {
          this.setState({value: e.target.value});
      },

      render: function () {
          return (
              <div>{this.state.value}
                  <input type="text" defaultValue={this.state.value || ''} value={this.state.value} 
onBlur={(e) => this.changeTo(e)} onChange={(e) => this.updateValue(e}/>
              </div>
          );
      }
like image 188
Arpit Avatar answered Sep 07 '25 20:09

Arpit