How to set a value for a span with React

0

I was trying to do that when the user pressed the submit button, he would check what the user entered, and if it was not valid he would send an error message through the span.Obs: I cut the code for easier reading, but the problem is in this part.

import React from 'react';

export class FormSignUp extends React.Component{
constructor(){
  super();
  this.state = {
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    rePassword: '',
    day:'default',
    month: 'default',
    year: 'default',
    gender:'1'
  };
}

  changeInp = e =>{
    this.setState({
      [e.target.name]: e.target.value
    });
  };
errors = {
  nameError: ''
}
  onSubmit = (e) => {
    e.preventDefault();
    if(this.state.firstName.length < 3){
      this.errors.nameError = 'ta errado isso dai';
    }
      alert('submit');
    console.log(this.state);
  }



  render(){
    return(
      <div className='formSignUp'>
        <div className='fullSameInputS'>
          <form>
            <div className='nameDiv halfInput'>
              <input type="text" name='firstName' value={this.state.firstName} onChange={e => this.changeInp(e)} className='signUpFstNameInput' placeholder='Nome'/>
              <span>{this.errors.nameError}</span>
            </div>
    
asked by anonymous 25.10.2017 / 18:30

1 answer

0

Just as you already use state to display firstName , you must use the state to return the error to be displayed on the screen. Since you created a errors property within its this scope, the render method will never be called (and consequently the component will not be updated on the screen), because React will only update its component if its state changes. / p>

The changes you can make to your code are these here

Update method that modifies error

onSubmit = (e) => {
  e.preventDefault();
  if(this.state.firstName.length < 3){
    this.setState({ nameError: 'ta errado isso dai' });
  }
    alert('submit');
  console.log(this.state);
}

Update tag span

<span>{this.state.nameError}</span>

Note that I removed the scope error , because you do not need it, if you use it, always use shallow objects (or objects with 1 level of housekeeping) in the state to help React make the shallow compare , if its component is PureComponent .

    
26.10.2017 / 20:02