1

Does anyone know how to make this code work in a React Functional Component?

onfocus="(this.type='date')" onblur="(this.type='text')"

I am trying to get placeholder text to appear prior to the user clicking on the input element. Then when clicked, the input will change to MM/DD/YYYY.

Trying to emulate something like this in my React project: https://stackoverflow.com/a/34565565/14677057

Would appreciate any help! Thank you!

Kevin Chen
  • 13
  • 1
  • 4

3 Answers3

3

Have a state variable for the type, then use it in what you render:

const Example = () => {
  const [type, setType] = useState('text');
  return (
    <input 
      type={type} 
      onFocus={() => setType('date')} 
      onBlur={() => setType('text')}
    />
  )
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

you can useRef for focusing. onBlur will work in camel case.

eg:
    function CustomTextInput(props) {
      // textInput must be declared here so the ref can refer to it
      const textInput = useRef(null);
      
      function handleClick() {
        textInput.current.focus();
      }
    
      return (
        <div>
          <input
            type="text"
            ref={textInput} />
          <input
            type="button"
            value="Focus the text input"
            onClick={handleClick}
          />
        </div>
      );
    }
Keerthi Vijay
  • 356
  • 2
  • 9
0

Handling events with react elements is syntactically different from DOM elements.

  • events are named using camelCase, rather than lowercase.
  • We need to pass a JSX function, rather than a string.

`

function HandleInputField(){
   const onChange=()=>{//your code}
   const onFocus=()=>{//your code}
   const onBlur=()=>{//your code}
   return <input onChange={} onFocus={} onBlur={}/>
 }

`

Bansl
  • 11
  • 2