简体   繁体   中英

no-unused-expressions in React with conditionals

I have a form that needs to validate a const first, if true, open the modal, if false, submit the form.

I did this, this works but I'm getting the error:

Expected an assignment or function call and instead saw an expression @babel/no-unused-expressions

modalOpen = () => this.setState({ showModal: true });

const validateType = !someAttribute && hasChange;

const submit = () => {
    validateType ? this.modalOpen() : handleSubmit();
};

// Do I need to have this submit here too?
<Form className={cn} onSubmit={isReadOnly ? () => {} : handleSubmit} readOnly={isReadOnly}>

    <Button
        type="button"
        onClick={submit}
    />
</Form>

The error occurs on this line here:

validateType ? this.modalOpen() : handleSubmit();

I looked at the documentation and I really don't understand why this error is happening.

If anyone can help me understand I would be very grateful.

Option 1 - replace ternary with if/else :

const submit = () => {
  if(validateType) this.modalOpen(); 
  else handleSubmit();
};

Option 2 - find the rule in your .eslint file, and change to rule to allow ternary expressions:

no-unused-expressions: ["error", { "allowTernary": true }]

Option 3 - ignore eslint for this line:

const submit = () => {
  // eslint-disable-next-line no-unused-expressions
  validateType ? this.modalOpen() : handleSubmit();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM