cphill
cphill

Reputation: 5914

Showing error on empty input field ReactJS

I am trying to enable/disable a form button based on if there are any characters in both the of the text input fields, but for some reason the state lengths are rendering an error with my conditional, despite when I log the state it shows up.

Error:

const isEnabled = this.state.subject.length > 0 && this.state.emails.length > 0; 
//Uncaught TypeError: Cannot read property 'length' of undefined

Full Code:

import React from 'react';

export default class EmailAnnotationForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            csrf: '',
            subject: '',
            emails: '',
            comment: ''
        }
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleFormSubmit = this.handleFormSubmit.bind(this);
        this.handleClearForm = this.handleClearForm.bind(this);
        this.input = React.createRef();
    }

    componentDidMount() {
        console.log(this.state.subject.length) // renders correct value => 0
        this.setState({subject: this.props.title });
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({
            [name]: value
        });
    }

    handleClearForm() {
        this.setState({
            csrf: '',
            subject: '',
            emails: '',
            comment: ''
        })
    }

    handleFormSubmit(event) {
        var emailSubject;  
        {
            this.state.subject ? emailSubject = this.state.subject : emailSubject = this.props.title
        }; //

        const body = {
            subject: emailSubject,
            emails: this.state.emails,
            comment: this.state.comment
        };

        event.preventDefault();
        var route = `${API_ROOT}` + '/api/annotation/' + this.props.annotationId + '/share/email';
        fetch(route,
            {
                method: 'POST', 
                body: JSON.stringify(body),
                compress: false,
                headers: { 
                    'X-CSRF-Token': this.props.csrf,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })  
            .then(data => {
                this.handleClearForm();
                this.props.shareFlashMessage('success');
                this.setState({'flash': 'success'});
                this.props.closeShareModal(false);
            }) 
            .catch(err => {
                console.log(err);
                this.props.shareFlashMessage('error');
                this.setState({'flash': 'error'});
            });
    }


    render() {
        var emailSubject;  
        {
            this.state.subject 
                ? 
            emailSubject = this.state.subject 
                : 
            emailSubject = this.props.title
        };

        console.log(this.state) // csrf: '', subject: undefined, emails: '', comment: ''
        console.log(this.state.subject) // renders undefined

        const isEnabled = this.state.subject.length > 0 && this.state.emails.length > 0; //Uncaught TypeError: Cannot read property 'length' of undefined

        return (
            <div className="annotation-footer__share-form-email">
                <form action={"/api/annotation/" + this.props.annotationId + "/share/email"} method="post" onSubmit={this.handleFormSubmit} name="annotationEmailShare" id="share-email-form">
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Subject:</b></p>
                        <input type="text" name="subject" className="form-control" defaultValue={this.props.title} onChange={this.handleInputChange}/><br />
                    </div>
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Emails (Comma separate each email address):</b></p>
                        <input type="text" name="emails" className="form-control" onChange={this.handleInputChange}/><br />
                    </div>
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Additional Comment (Optional):</b></p>
                        <textarea name="comment" rows="4" className="form-control" onChange={this.handleInputChange}></textarea><br />
                    </div>
                    <button type="submit" disabled={!isEnabled}>Send Email</button>
                </form>
            </div>
        )
    }
}

Upvotes: 1

Views: 2761

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104359

It seems this.props.title is undefined.

To solve the issue, put the check on this.props.title value, and update the state only if it has a valid value. Like this:

componentDidMount() {
  if(this.props.title)
    this.setState({ subject: this.props.title });
}

Suggestion:

Instead of updating subject with props value in didMount method, do it in constructor itself, Like this:

this.state = {
  csrf: '',
  subject: props.title || '',
  emails: '',
  comment: ''
}

Upvotes: 1

Related Questions