Borislav Hadzhiev
Last updated: May 3, 2022
Photo from Unsplash
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.
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
".
The 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" />
The 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.
You 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.
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
.