DEV Community

loading...

Undefined variable in react, what I don't get?

grzesiekkozdroj profile image Grzesiek Kozdroj ・1 min read

It will say that name and are undefined but I don't know why and how to fix it.

My code:

Discussion (1)

pic
Editor guide
Collapse
grzesiekkozdroj profile image
Grzesiek Kozdroj Author

const phoneExp = /\(?![0])|[0])[0-9](?[0-9])?[0-9]*$/;

const formValid = formErrors => {
let valid = true;
Object.values(formErrors).forEach(val => {
val.length > 0 && (valid = false);
});

return valid

}

class App extends React.Component {
constructor(props) {
super(props)
this.state={
nameInput: null,
phoneInput: null,
formErrors:{
nameInput:"",
phoneInput:""
}
}
}
handleSubmit = e =>{
e.preventDefault();
if(formValid(this.state.formErrors)){
console.log(
--SUBMITTED--
--nameInput:${this.state.nameInput}
--phoneInput:${this.state.phoneInput}
);
}else{
console.log(error)
}
}

handleChange = e => {
    e.preventDefault();
    const {name, value} = e.taret;console.log(name,value)
    let formErrors = this.state.formErrors;

    switch(name){
        case 'nameInput':
            formErrors.nameInput = value.length < 3 && value.length > 0 ? "name too short" : "please enter a name";
        break;
        case 'phoneInput':
            formErrors.phoneInput = phoneExp.test(value) && value.length > 0 ? "please enter a phone number" : "bad phone number";
        break;
        default:
            break;
    }
}

render() {
    return (
        <>
            <h1>here we go again</h1>
            <form onSubmit={this.handleSubmit}>
                <div className="nameInput">
                    <label htmlFor="nameInput" noValidate >Name:</label>
                    <input 
                        type="text" 
                        noValidate 
                        name="nameInput"
                        onChange={this.handleChange}
                    />
                </div>
                <div className="phoneInput">
                    <label htmlFor="phoneInput" noValidate >Phone:</label>
                    <input 
                        type="text" 
                        noValidate 
                        name="phoneInput"
                        onChange={this.handleChange}
                    />
                </div>
                <div className="saveNumbers">
                    <button type="submit">save</button>
                </div>
            </form>
        </>
    )

}

}

document.addEventListener('DOMContentLoaded', function () {
ReactDOM.render(
,
document.getElementById('app')
);
});