Change the input type on-focus in JSX doesn't work
Asked Answered
R

3

5

I have a text field which has the placeholder "Dates From". what I wanna do is to change It's input box type to a date type on the focus event. But

but the below mentioned solution doesn't work with JSX.

<input placeholder="Date" type="text" onFocus="(this.type='date')"  id="date"> 

How to make this thing work on ReactJs or How to achieve the same goal?

Refrigerant answered 24/12, 2018 at 2:37 Comment(1)
Possible duplicate of React changing input type via eventDimmick
U
8

Using an anonymous function should work, with e.target:

<input placeholder="Date" type="text" onFocus={(e) => e.target.type = 'date'}  id="date" /> 

You can see it in action here.

Ugrian answered 24/12, 2018 at 2:43 Comment(0)
M
1
Try this code     
handleFocus(event) {
        event.target.type = 'date'; 
      }

      render() {
        return (     
            <label>
              Name:
              <input type="text" placeholder="please Enter date"  onFocus={this.handleFocus.bind()} /> 
            </label>

        );
      }
Microcline answered 24/12, 2018 at 9:3 Comment(0)
C
0

Perhaps you could take a state based approach to this, where you would update the state of the component to track the type of the input field when onFocus occours by doing something like this:

onFocus={ () => this.setState({ typeOfFocused : 'date' }) } 

Doing this would trigger a re-render which in turn would cause the input element's type to switch to date via the following:

render() {

     // Extract typeOfFocused from state
     const { typeOfFocused } = this.state

     // Render input type with typeOfFocused if present, or as text by default
     return (<input placeholder="Date" 
             type={ typeOfFocused || 'text' } 
             onFocus={ () => this.setState({ typeOfFocused : 'date' }) } 
             onBlur={ () => this.setState({ typeOfFocused : '' }) }
             id="date">)
 } 

Here's a working sample

Creuse answered 24/12, 2018 at 2:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.