user13780186
user13780186

Reputation:

How to set the field2 and field3 to required based on the field1 value in react

 Schema.model({
    field1: StringType(),
    field2: StringType(),
    field3: StringType()
    })

return (
 <Form
            model={model}
          >
<FormControl name="field1" />
<FormControl name="field2" />
<FormControl name="field3" />
</Form>
)

How to set the field2 and field3 to required field?

What I'm trying to do is when field is equal to jake the field2 and field3 will be required. but when its not equal to jake then its not required.

I tried to use the onChange on the field1 but it doesn't work. also I tried the addRule in field2 & field3 but it doesn't work also.

addRule((value, data) => { 
 if (data.field1 ==='jake') {
 return true;
} return false;
}

I want to apply this in field2 and field3 StringType().isRequired('Required field') when the value in field1 is jake.

Upvotes: 1

Views: 198

Answers (2)

Supperhero
Supperhero

Reputation: 1191

Sounds like an issue with the render cycle. How, exactly, did you implement changing the required attribute on change? You need to do it through a state variable so that react knows to re-render when it changes.

Upvotes: 0

Odasaku
Odasaku

Reputation: 367

Add rule looks correct to me, but if it's not working, maybe try this in you JSX:

  {this.state.field1 === 'jake'?
        <FormControl name="field2" required/>
        <FormControl name="field3" required/>
       :
       <FormControl name="field2" />
        <FormControl name="field3" />

and for field on onChange={e => this.setState({field1: e.target.value})}

Note: I am not sure if this would be the optimal way, but it should work.

Upvotes: 0

Related Questions