Home > Software engineering >  how to change both input type and max value in react input tag during onfocus?
how to change both input type and max value in react input tag during onfocus?

Time:06-20

i have an input tag .by default it will have type as text but during onfocus type should be changed to date and max should be changed to current date. initially i'm using input type as text since i want an placeholder which says 'Select start date'. i'm building an React application. how to do this?

CodePudding user response:

In plain JS you could just do somthing like this (shoutouts to TRiNE for originally posting the today's-date-code):

const input = document.getElementById('myInput')

input.addEventListener('focus', changeToDateType)

function changeToDateType(){
  input.type = "date"
  input.max = new Date().toISOString().split("T")[0]
}
<input id="myInput" placeholder="Enter date here...">

CodePudding user response:

var Foo = React.createClass({
  getInitialState: function () {

    return {
      type: 'text'
    };
  },
  onFocus: function () {

    this.setState({
      type: 'date'
    });
  },
  onBlur: function () {

    this.setState({
      type: 'text'
    });
  },
  render: function () {

    return(
      <input 
        type={ this.state.type } 
        onFocus={ this.onFocus } 
        onBlur={ this.onBlur } 
        placeholder="Enter your date here."
      />
    )
  }
});

React.render(<Foo/>, document.body);
  • Related