skip to Main Content

I am currently trying to clear the input field every time I try to submit the form but the content won’t disappear

export default function MainContent() {
    const [note, setNotes] = React.useState('')
    const { addToContainer } = React.useContext(notesContext)
    const useRef = React.useRef(null)
    function change(e) {
        const { value, name, id } = e.target
        setNotes(prevNote => {
            return {
                ...prevNote,
                [name] : value
            }    
        })
    }
    function handleSubmit(e) {
        e.preventDefault()  
        addToContainer(note)
   }

    return (<div><div className="main">Here are your notes!</div>
        <form onSubmit={(e) => handleSubmit(e)}><textarea  name="notes" onChange={(e) => change(e)} id="notes" value={note.notes} />
        <button>Submit here</button>    
        </form>
    </div>)    
}

I have tried to setNotes('') when submitting it but that does nothing.

3

Answers


  1. You could extend the handleSubmit() function to reset the useState():

    function handleSubmit(e) {
        e.preventDefault();
        addToContainer(note);    // Handle Form
        setNotes('');            // Reset notes
    }
    
    <form onSubmit={(e) => handleSubmit(e)} ...>
    

    Small demo based on your code:

    const { useState } = React;
    
    const Example = () => {
    
        const [note, setNotes] = React.useState('')
        
        function change(e) {
            const { value, name, id } = e.target
            setNotes(prevNote => {
                return {
                    ...prevNote,
                    [name] : value
                }    
            })
        }
        
        function handleSubmit(e) {
            e.preventDefault();
            // addToContainer(note);                // Handle Form
            console.log('Submit: ', note)           // Demo handler
            setNotes({ notes: ''});                 // Reset notes
        }
    
        return (
            <div>
                <div className="main">Here are your notes!</div>
                <form onSubmit={handleSubmit}><textarea  name="notes" onChange={(e) => change(e)} id="notes" value={note.notes} />
                    <button>Submit here</button>    
                </form>
            </div>
        )    
    }
    
    ReactDOM.render(<Example />, document.getElementById("react"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
  2. There seems to be an inconsistency on whether note is a string:

    const [note, setNotes] = React.useState('')
    

    Or an object:

    setNotes(prevNote => {
        return {
            ...prevNote,
            [name] : value
        }    
    })
    

    The markup expects an object (with a notes property):

    <textarea name="notes" onChange={(e) => change(e)} id="notes" value={note.notes} />
    

    This could very well cause confusion in the rendering of the form element because sometimes the value is undefined (whether initially or after setting state back to '', in both cases note.notes is undefined), which could be switching this back and forth from a controlled to uncontrolled form element.

    At the very least, this should be consistent. If the intent is to use an object, initialize it as such:

    const [note, setNotes] = React.useState({notes:''});
    

    And reset it by resetting that object:

    setNotes({notes:''});
    

    Example:

    function MainContent() {
      const [note, setNotes] = React.useState({ notes: "" });
      //const { addToContainer } = React.useContext(notesContext)
      //const useRef = React.useRef(null)
      function change(e) {
        const { value, name } = e.target;
        setNotes((prevNote) => {
          return {
            ...prevNote,
            [name]: value
          };
        });
      }
      function handleSubmit(e) {
        e.preventDefault();
        //addToContainer(note)
        setNotes({ notes: "" });
      }
    
      return (
        <div>
          <div className="main">Here are your notes!</div>
          <form onSubmit={(e) => handleSubmit(e)}>
            <textarea
              name="notes"
              onChange={(e) => change(e)}
              id="notes"
              value={note.notes}
            />
            <button>Submit here</button>
          </form>
        </div>
      );
    }
    
    ReactDOM.render(<MainContent />, document.getElementById("app"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="app"></div>

    Alternatively, if you would rather just use a simple string instead of an object:

    function MainContent() {
      const [note, setNotes] = React.useState("");
      //const { addToContainer } = React.useContext(notesContext)
      //const useRef = React.useRef(null)
      function change(e) {
        const { value } = e.target;
        setNotes(value);
      }
      function handleSubmit(e) {
        e.preventDefault();
        //addToContainer(note)
        setNotes("");
      }
    
      return (
        <div>
          <div className="main">Here are your notes!</div>
          <form onSubmit={(e) => handleSubmit(e)}>
            <textarea
              name="notes"
              onChange={(e) => change(e)}
              id="notes"
              value={note}
            />
            <button>Submit here</button>
          </form>
        </div>
      );
    }
    
    ReactDOM.render(<MainContent />, document.getElementById("app"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="app"></div>

    The code used to update the state in the change function implies that the intent is to add other fields to the object, though the name of the object doesn’t imply that at all. But the point is to pick one or the other.

    Login or Signup to reply.
  3. I think you should not give an object to the value of <textarea />,
    I mean that the value must be a string type.
    You said that you tried setNotes(''), which didn’t work at all, (Have you changed the value from note.notes to note), I think the following code must be like that:

    export default function MainContent() {
      const [note, setNote] = React.useState(''); // Change 'setNotes' to 'setNote'
      const { addToContainer } = React.useContext(notesContext);
      const useRef = React.useRef(null);
    
      function change(e) {
        const { value } = e.target;
        setNote(value); // Set 'note' directly as a string
      }
    
      function handleSubmit(e) {
        e.preventDefault();
        addToContainer(note);
    
        // Clear the input field after submitting the form
        setNote(''); // Reset 'note' to an empty string
      }
    
      return (
        <div>
          <div className="main">Here are your notes!</div>
          <form onSubmit={(e) => handleSubmit(e)}>
            <textarea name="notes" onChange={(e) => change(e)} id="notes" value={note} />
            <button>Submit here</button>
          </form>
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search