NewOldMax / react-form-validator-core

Core validator component for react forms
MIT License
94 stars 44 forks source link

onChange, setState doesn't work! #43

Closed Vladimirtishenko closed 5 years ago

Vladimirtishenko commented 5 years ago

Hi. Many things doesn't work. I have code example:

<ValidatorForm instantValidate={false} onSubmit={::this.submit} className="form">
 <Input
    validators={['required', 'matchRegexp:^@+.?' ]}
    errorMessages={['this field is required', 'telegramm link should be like in example @your_name']}
    value={contactInfo && contactInfo.telegramAccount}
    name="contactInfo.telegramAccount"
 />
</ValidatorForm>

and part of my Input component:

class Text extends ValidatorComponent {
 static propTypes = {......}
 static defaultProps = {......}
 constructor(props){
    super(props);
    this.state = {
        ...Text.defaultProps,
        ...this.props,
        ...{id: uniqid(this.props.name + '-')}
    }
 }

errorText() {....From example...}

 onChange(event){
     let value = event && event.target && event.target.value || '';
     this.setState({
            value: value
     })
}
render(){
    <>
       <input
          ref={(r) => { this.input = r; }}
          onChange={::this.onChange}
          value={this.state.value}
          name={this.state.name}
        />
        {this.errorText()}   
   </>
 }
}

1: when page is loaded validation start to run even if instantValidate={false}. 2: when i try to change input value -validation started again. 3: I can't change input value through method onChange, value doesn't change because of method in your component getDerivedStateFromProps 4: When i submit the form your component get old value that was when the page loaded, and validation passing, however value in field have already deferent value.

Can you clarify something?

NewOldMax commented 5 years ago

Hi can you reproduce your issue here? It's not so clear from your pieces of code

Vladimirtishenko commented 5 years ago

Sure https://codesandbox.io/s/538v4k08yk

NewOldMax commented 5 years ago

So here is your fixed example

This library works with controlled components. It means you must control your Input component outside of itself. So you must move onChange to upper level and control value in Main component.

Vladimirtishenko commented 5 years ago

Did you mean i must change the props all the time?

NewOldMax commented 5 years ago

Yes, this is how it's working

Vladimirtishenko commented 5 years ago

Will be better if it works without pass some props from outside) Because of it we should make another one wrapper)

NewOldMax commented 5 years ago

¯_(ツ)_/¯