0

I am trying to validate an email TextField with a button. I am using props to store the email TextField's error state.

Email Textfield code:

<TextField
required
error={values.emailInvalid}
id="emailAddress"
name="emailAddress"
label="Email Address"
onChange={handleChange("email")}
defaultValue={values.email}
fullWidth
autoComplete=""
variant="standard"
/>

Button code:

var re = /\S+@\S+\.\S+/;
    var testEmail = re.test(this.props.values.email);
    if (this.props.values.email.length === 0 || !testEmail) {
      this.props.values.emailInvalid = true;
    } else {
      this.props.values.emailInvalid = false;
      //go next page
    }
 console.log(this.props.values.emailInvalid);

The "emailInvalid" boolean is updating properly according to the console output, but the TextField does not visibly show the red error state is "emailInvalid" is set to true.

3 Answers3

0

You cannot just assign the value of emailInvalid with this.props.values.emailInvalid = true.
If values is a state object, you need to also pass the setState function in props and use it like below

this.props.setState({ emailInvalid:true })

Also, you should use this.props.values instead of values in the TextField component

0

You need to use setState to mutate the component state for example

SetEmailInvalid(true);

for Class based components:

this.setState({emailInvalid: true});

You can't edit react state directly. Open This Link To See Why

0

The way you are changing things in React is not supported. you can follow this guide: First of all: PROPS ARE READONLY and you can not change them. Second, for changing things that have to be shown in the browser as it changes is done via State. to fix your error first import useState like: (we are using states as hook)

import {useState} from "react";

then you have to use your state and initialize the amount:

const [emailIsValid, setEmailIsValid] = useState(true)

this will set the initial value of the emailIsValid to true.

now whenever you want to change the value of emailIsValid , you have to call the set function and set the value like: setEmailIsValid(false)

now you can use the emailIsValid anywhere in your react component.

Shayan Faghani
  • 243
  • 1
  • 9