tnoel999888
tnoel999888

Reputation: 654

React how to display label even when empty

I have a label displaying a string from a text input that the user fills in.
The string is stored in the question variable and it is displayed as follows:

<label
  className={css('form-title-label')}>
    {question}
</label>

However, when the user hasn't written anything in the text input the variable is empty and the label is not displayed, which causes the surrounding components to move up and fill the space.
How do I ensure the label is present even when it is empty to stop everything from moving around?

Upvotes: 1

Views: 2314

Answers (2)

mehmetseckin
mehmetseckin

Reputation: 3107

You could display a spacer element conditionally, e.g.

const spacer = (<span>&nbsp;</span>);

return (
  <label
    className={css('form-title-label')>
      {question || spacer}
  </label>
);

Upvotes: 3

Holly E
Holly E

Reputation: 569

I would just give the variable a default value of something like " " so that there is something there at all times.

const question = this.props.question || " "

Upvotes: 1

Related Questions