Last updated: Apr 7, 2024
Reading time·3 min
Use the placeholder
prop to set a placeholder on an input field in React.
The placeholder text of an input field is shown until the user types something in the field.
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> ); }
We used the placeholder
prop to set
placeholder text
on an input field.
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
".
If you need to validate an email input field, check out the following article.
placeholder
prop to a stringThe first two examples show how to set the placeholder
prop on an input field
to a string.
<input type="text" placeholder="Your first name" /> <input type="number" placeholder="Your fav number" />
If you need to set a placeholder on a select tag, click on the link and follow the instructions.
placeholder
prop to a variableThe third example uses a variable for the placeholder text.
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.
placeholder
propYou can also conditionally set the placeholder
prop on an input field.
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.
If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.
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
.
You can imagine that the value before the colon is the if
block and the value
after the colon is the else
block.
You can learn more about the related topics by checking out the following tutorials: