Search code examples
reactjscomponents

React Component getting displayed and disappearing immediately


I'm learning React and as part of that I have tried some code for making a notebook kind of app where I get to add notes and then they are displayed dynamically

When I'm trying to add a note, the new react component(note) is getting displayed but immediately getting disappeared. As if the entire browser is refreshed. Attaching my code. This is my first time asking the question so not even sure how of it was understandable.

https://codesandbox.io/s/keeper-part-3-starting-forked-0mf1cs


Solution

  • For most of the modern browsers the default type of button tag is submit (https://stackoverflow.com/a/31644856/7399478). So, the form is submitted when you click the button and the page is refreshed after submit.

    You need to change add type="button" to your button tag in your CreateArea.jsx component in order to prevent submitting the form like:

    <button
      type="button"
      onClick={() => {
        props.onAdd(note);
      }}
    >
      Add
    </button>