ArvindD.
ArvindD.

Reputation: 49

How to render empty element to dom in React?

I'm trying to render a element to the dom that contains a empty value when the page is loaded initially

<small className="error-message">
   <p id="error-msg">{this.state.errorMessage}</p>
</small>

errorMessage is initially set to an empty string and I set the error message when some fields in my form are not completed

        this.state = {
            firstName: '',
            lastName: '',
            email: '',
            username: '',
            password: '',
            confirmPassword: '',
            errorMessage: ''
        }

    async handleSubmit(event) {
        event.preventDefault()
        if(!this.state.firstName || !this.state.lastName || !this.state.email || !this.state.username || !this.state.password || !this.state.confirmPassword){

            return this.setState({errorMessage: 'Please complete all fields'})
        }

My problem is that react wont add the small element to the Dom unless errorMessage is set. This makes my form expand vertically to show the error message. Is there any way I can make react render the small element regardless of what the value of errorMessage is so my form remains the same height?

Upvotes: 0

Views: 357

Answers (1)

Mario Vernari
Mario Vernari

Reputation: 7306

I would set a minimum height for the fragment:

<small className="error-message" style={{ minHeight: 30 }}>
   <p id="error-msg">{this.state.errorMessage}</p>
</small>

Upvotes: 1

Related Questions