Jacobdo
Jacobdo

Reputation: 2021

DOM does not update on value change

I am trying to set up a simple form using a function component using a next.js project:

const Form = () => {

    let error = false 
    const handleNameSubmit = (e) =>  {
        e.preventDefault()

        const name = e.target.name.value.trim()

        if(!! name.length) {
            error = false
        } else {
            error = 'Please enter your name'
        }
    }

    return (
        <>
            <form onSubmit={handleNameSubmit}>
                <h1>I’d like to know how to address you, 
                please type in your name</h1>
                <input type="text" name="name" placeholder="Your name"/>
                {!!error && (<p>{error}</p>)}
                <button type="submit">Next</button>
            </form>
        </>
    )
}

I am doing some trivial validation i.e. checking if any value is entered in the name input and displaying an error, if the field is empty.

However, when I set the value of error on page load to be something, it shows in the DOM, but if I manipulate it later, the DOM does not update. I am new to next.js.

Upvotes: 1

Views: 640

Answers (1)

user11910739
user11910739

Reputation:

You have to use state variable to achieved your goal. Simply convert error in state variable and it will work.

const Form = () => {
  const [error, setError] = useState(false);

  const handleNameSubmit = (e) => {
    e.preventDefault();
    const name = e.target.name.value.trim();
    setError(name.length ? false : 'Please enter your name');
  }

  return (
    <>
      <form onSubmit={handleNameSubmit}>
        <h1>I’d like to know how to address you,
                please type in your name</h1>
        <input type="text" name="name" placeholder="Your name" />
        <button type="submit">Next</button>
        {error && <p>{error}</p>}
      </form>
    </>
  )
}

I have created small demo for you.
https://stackblitz.com/edit/react-7kat5c

Hope this will help you!

Upvotes: 2

Related Questions