Rohan
Rohan

Reputation: 33

event.preventDefault( ) is NOT working in React

Unable to get values in console! What am I doing it incorrectly?

Attached below is the functional component of React

The Handler Functions

import React, { useState, useRef } from 'react';

const SimpleInput = (props) => {
  const nameInputRef = useRef();
  const [enteredName, setEnteredName] = useState('');

  const nameInputChangeHandler = (event) => {
    setEnteredName(event.target.value);
  };

  const formSubmissionHandler = (event) => {
    event.preventDefault();
    console.log(enteredName);

    const enteredName = nameInputRef.current.value;
    console.log(enteredName);
  };

  return (
    <form>
      <div className="form-control" onSubmit={formSubmissionHandler}>
        <label htmlFor="name">Your Name</label>
        <input
          ref={nameInputRef}
          type="text"
          id="name"
          onChange={nameInputChangeHandler}
        />
      </div>
      <div className="form-actions">
        <button>Submit</button>
      </div>
    </form>
  );
};

export default SimpleInput;

Upvotes: 0

Views: 795

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

formSubmissionHandler should have on the form element rather than the div element.

 return (
    <form onSubmit={formSubmissionHandler}>
      <div className="form-control">
        <label htmlFor="name">Your Name</label>
        <input
          ref={nameInputRef}
          type="text"
          id="name"
          onChange={nameInputChangeHandler}
        />
      </div>
      <div className="form-actions">
        <button>Submit</button>
      </div>
    </form>
  );

Upvotes: 1

Related Questions