Home > front end >  How to use setTimeout in react for if statement?
How to use setTimeout in react for if statement?

Time:09-23

I like to use only placeholder without label for inputs/forms. Therefore i created a onClick -> set type from text to date. But if someone has a bad memory and dont know what date to fill in, I created a onm ouseleave -> set type from date to text, if its empty. But if someone want to fill his birthday and the mouse leaves accendently, they will give me a text instead of a date. Therefore I want to use a setTmeout but it doesn't work as planned.

const [type, setType] = useState("text")

const handleDate = () => {
  setType("date")
} 

const handleText = () =>{  
  if(values.birthday === ""){
  setType("text")}
}
<input  
     onChange={handleChange}
     value={values.birthday}
     type={type}
     name="birthday"
     placeholder="birthday"
     onClick={handleDate}
     onm ouseLeave={setTimeout(handleText, 3000)}/>

by using onm ouseLeave={setTimeout(handleText, 3000)}/> the input field is deselected and i can't type anything in.

I want that the if-query will be checked after 3 seconds and am able to type something in

CodePudding user response:

try this:

<input  
     onChange={handleChange}
     value={values.birthday}
     type={type}
     name="birthday"
     placeholder="birthday"
     onClick={handleDate}
     onm ouseLeave={() => setTimeout(handleText, 3000)}/> 

the way you're doing currently it is immediately calling the setTimeout on render, you need to put it as a function

CodePudding user response:

This is very weird UX design, I doubt your users will like it. No one expects that moving the mouse out of the input would replace the contents of the input a few seconds later. And did you consider that people may use a touch screen? Or move to the next input with the Tab key?

How about using a more conventional UX, for example title if you don't want labels?

  • Related