Set a placeholder on an Input field in React

avatar

Borislav Hadzhiev

Last updated: May 3, 2022

banner

Photo from Unsplash

Set a placeholder on an Input field in React #

Use the placeholder prop to set a placeholder on an input field in React, e.g. <input type="text" placeholder="Your first name" />. The placeholder text of an input field is shown until the user types something in the field.

App.js
export default function App() { const placeholder = 'Your message'; return ( <div> <input type="text" placeholder="Your first name" /> <input type="number" placeholder="Your fav number" /> <input type="text" placeholder={placeholder} /> <input type="text" placeholder={'hi'.length === 2 ? 'My placeholder' : 'Your placeholder'} /> </div> ); }

input placeholder

We used the placeholder prop to set placeholder text on an input field.

The placeholder attribute is a string that provides a hint to the user as to what kind of information is expected in the field.

For example, for an email field, we could have placeholder text of "Your email" or "e.g. john-smith@gmail.com".

The first two examples show how to set the placeholder prop on an input field to a string.

App.js
<input type="text" placeholder="Your first name" /> <input type="number" placeholder="Your fav number" />

The third example uses a variable for the placeholder text.

App.js
export default function App() { const placeholder = 'Your message'; return ( <div> <input type="text" placeholder={placeholder} /> </div> ); }

The curly braces in placeholder={placeholder} mark the beginning of an expression that has to be evaluated.

You can also conditionally set the placeholder prop on an input field.

App.js
export default function App() { return ( <div> <input type="text" placeholder={'hi'.length === 2 ? 'My placeholder' : 'Your placeholder'} /> </div> ); }

We used a ternary operator which is very similar to an if/else statement.

The part before the question mark gets evaluated and if it returns a truthy value, the operator returns the value before the colon, otherwise it returns the value after the colon.

The ternary operator in the example checks if the length of the string hi is equal to 2 and if it is, it returns the string My placeholder, otherwise it returns Your placeholder.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.