How to set a placeholder on an input field in React?

To set a placeholder on an input field, use the placeholder prop.

The placeholder text provides a hint to the user as to what kind of value is expected in the field. It is displayed on the input element until the user types something in the field.

App.js
import React from 'react';

export default function App() {
  let hintText = 'Last Name';
  let country = 'India';

  return (
    <div>
      <input type="text" placeholder="First Name" />
      <input type="text" placeholder={hintText} />
      <input
        type="text"
        placeholder={country === 'India' ? 'Salary in Rs.' : 'Salary in Dollar'}
      />
    </div>
  );
}

Output

How to set a placeholder on an input field in React

The example shows three different ways to set the placeholder prop on the input element.

1. You can directly set the hint string to the placeholder prop.

App.js
import React from 'react';

export default function App() {

  return (
    <div>
      <input type="text" placeholder="First Name" />
      <input type="email" placeholder="Email Address" />
    </div>
  );
}

2. You store the placeholder text to the variable. And then assign that variable to the placeholder prop.

App.js
import React from 'react';

export default function App() {
  let hintText = 'First Name',
  hintText2 = "Email Address";

  return (
    <div>
      <input type="text" placeholder={hintText} />
      <input type="email" placeholder={hintText2} />
    </div>
  );
}

Any JavaScript expression to be evaluated is wrapped in curly braces.

3. You can also use a ternary operator to set the value to the placeholder prop.

App.js
import React from 'react';

export default function App() {
  let country = 'India';

  return (
    <div>
      <input
        type="text"
        placeholder={country === 'India' ? 'Salary in Rs.' : 'Salary in Dollar'}
      />
    </div>
  );
}