How to set placeholder in input type date [React]

Viewed 4387

I want to know how to set placeholder in input date.

this is my code

<input type="text" onChange={(e) => { setbirth(moment(e.target.value).format('YYYYMMDD')) }} placeholder="생년월일" onFocus="(this.type = 'date')" onBlur="(this.type='text')" />

I've looked through the question, but using this code throws an error.

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


Warning: Expected `onFocus` listener to be a function, instead got a value of `string` type.
Warning: Expected `onBlur` listener to be a function, instead got a value of `string` type.

Is there any way to change it without error?

4 Answers
import React , { useRef } from "react";

const App= () => {
  const ref = useRef();
  return (
    <div>
      <input
        type="date"
        ref={ref}
        onChange={(e) => console.log(e.target.value)}
        onFocus={() => (ref.current.type = "date")}
        onBlur={() => (ref.current.type = "date")}
      />
    </div>
  );
}
export default  App

useRef is not recommended here as it doesn't helps in re-rendering the component and hence it will not change the type of input. The better approach is to initialize it as type "text" and change the types based on the events on onFocus and onBlur. For your use case, please go through the code below.

export default function App() {
  return (
    <div>
      <input
        type="text"
        onChange={(e) => console.log(e.target.value)}
        onFocus={(e) => (e.target.type = "date")}
        onBlur={(e) => (e.target.type = "text")}
      />
    </div>
  );
}

The error is because onFocus and onBlur are event emitters that expect to fire a callback. In your code, onFocus and onBlur is a statement instead of a callback and thus the error.

You can use react RefObject to do it easily. Reference:

import { useRef } from "react";

export default function App() {
  const ref = useRef();
  return (
    <div>
      <input
        type="text"
        ref={ref}
        onChange={(e) => console.log(e.target.value)}
        onFocus={() => (ref.current.type = "date")}
        onBlur={() => (ref.current.type = "text")}
      />
    </div>
  );
}

Edit exciting-stonebraker-jq0f4

import { useRef } from "react";

export default function App() {
  const ref = useRef();
  return (
    <div>
      <input
        type="date"
        ref={ref}
        onChange={(e) => console.log(e.target.value)}
        onFocus={() => (ref.current.type = "date")}
        onBlur={() => (ref.current.type = "date")}
      />
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Related