-1

I got this code from react bootstrap website https://react-bootstrap.github.io/components/forms/ I will like to know the use of the following in the code

  • this.handleChange = this.handleChange.bind(this)
  • The use of making the value in this.state = { value: '' }; }
    empty
  • The use of setting the validationState attribute in validationState={this.getValidationState()}
  • And the use of setting two renders, why not just one render and is it possible to set more than one render

        class FormExample extends React.Component {
        constructor(props, context) {
        super(props, context);
        this.handleChange = this.handleChange.bind(this);
    
         this.state = {
       value: ''
       };
       }
    
       getValidationState() {
       const length = this.state.value.length;
       if (length > 10) return 'success';
       else if (length > 5) return 'warning';
       else if (length > 0) return 'error';
        return null;
        }
    
        handleChange(e) {
        this.setState({ value: e.target.value });
        }
    
         render() {
         return (
         <form>
         <FormGroup
         controlId="formBasicText"
      validationState={this.getValidationState()}
    >
      <ControlLabel>Working example with validation</ControlLabel>
      <FormControl
        type="text"
        value={this.state.value}
        placeholder="Enter text"
        onChange={this.handleChange}
      />
      <FormControl.Feedback />
      <HelpBlock>Validation is based on string length.</HelpBlock>
    </FormGroup> </form>
        );
        }
        }
    
    render(<FormExample />);
    
Paul
  • 263
  • 4
  • 21

1 Answers1

3
  1. this.handleChange = this.handleChange.bind(this): This is to make it so you can use the variable "this" inside of handlechange()
  2. By setting a blank value, this key will not be empty in the future if you try to reference it without a value being set
  3. validationState is being passed into FormGroup as a property
  4. The renders are not in the same class so the FormExample is being rendered by something else outside it.

Hope that helps

greendemiurge
  • 509
  • 3
  • 11
  • What's the use of setting the validationState as a property – Paul Jun 21 '18 at 15:07
  • 2
    The FormGroup element doesn't know what the state of validation is unless you pass it in (https://medium.com/react-tutorials/react-properties-ef11cd55caa0). This means that inside of the FormGroup you can check this.props.validationState and see if any of the elements are in an error state. You will also frequently see syntax that looks like { validationState, someOtherProp } = this.props; This is known as destructuring and is equivalent to validationState = this.props.validationState; someOtherProp = this.props.someOtherProp; (https://wesbos.com/destructuring-objects/). – greendemiurge Jun 21 '18 at 15:17