How to set a value for a span with React

Asked

Viewed 229 times

1

I was trying to do that when the users pressed the button of Ubmit, it checked what the user entered, and if it was not valid it sent an error message through the span.Note:I cut the code to make it easier to read, but the problem ta 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>

1 answer

1


Just like you already use state to display the firstName, vc must use the state to return the p/ error to be displayed on the screen. How you created a property errors within its scope this, 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.

The changes you can make to your code are these

Update the method that modifies the 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 the tag span

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

Notice that I have removed the scope error, Because you don’t need it, if you use it, always use it shallow objects (or c/1 level objects) in the state to help React do the shallow compare, if its component is PureComponent.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.