How do I make my React/Bootstrap 4 validation error visible?

Viewed 7195

I'm using React 16.13.0 and Bootstrap 4. I have a React component (src/components/Input.jsx),

import React from 'react';
import {FormControl, FormLabel} from 'react-bootstrap';

const Input = (props) => {
    return (
  <div className="form-group">
      <FormLabel>{props.title}</FormLabel>
      <FormControl
            type={props.type}
            id={props.name}
            name={props.name}
            value={props.value}
            placeholder={props.placeholder}
            onChange={props.handleChange}
          />

      {props.errors && props.errors[props.name] && (
          <FormControl.Feedback>
                 {props.errors[props.name].map((error, index) => ( 
                     <div key={`field-error-${props.name}-${index}`} className="fieldError">{error}</div>
                 ))} 
          </FormControl.Feedback>
      )}
  </div>
    )
}

export default Input;

in which I'd like to display an error message if their is a form validation error returned from form submission.

  async handleFormSubmit(e) {
    e.preventDefault();
    const NC = this.state.newCoop;
    delete NC.address.country;

    try {
      const response = await fetch('/coops/',{
        method: "POST",
        body: JSON.stringify(this.state.newCoop),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      });
      
      if (response.ok) {
        const result = await response.json();
        console.log('_result_: ', result);
        return result;
      }
      throw await response.json();
    } catch (errors) {
      console.log('_error_: ', errors);
      this.setState({ errors });
    }
  }

However, when there is an error, although I can see in my HTML that the DIV with the error message is present, it is not visible. What am I missing? I'm guessing bootstrap provides some standard way of making my element visible.

2 Answers

To get visible error feedback, set isInvalid={Boolean(props.errors[props.name])} for FormControl and type="invalid" for FormControl.Feedback.

Consider destructuring the props to simplify your code.

Looks like you are setting error state incorrectly? In your comments, the server returns "error: {phone: Array(1), web_site: Array(1)}" and you are setting state like this this.setState({ errors }). With this, your error state will still be your initial state.

Try something like this.setState({ errors: response.error })

Related