Rusty
Rusty

Reputation: 37

React onClick function call refreshes app

I'm making a simple note taking app in the style of google keepnote. When I press the the add button from the create are component it calls the function in the app component that will add the note to an array for rendering. The function call works just fine but then the whole app refreshes and any data is lost.

I cant work out what is causing the refresh.

the App component:

import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App() {
  const [notes, setNotes] = useState({ id: "", title: "", content: "" });

  function addNote(note) {
    console.log(note);
  }

  return (
    <div>
      <Header />
      <CreateArea newNote={addNote} />
      <Note key={1} title="Note title" content="Note content" />
      <Footer />
    </div>
  );
}

export default App;

The CreateArea component:

import React, { useState } from "react";

function CreateArea(props) {
  const [note, setNote] = useState({ title: "", content: "" });

  function handleChange(event) {
    if (event === null || event === undefined) return;

    const { name, value } = event.target;

    if (name === "title") {
      setNote(prevValue => {
        return {
          title: value,
          content: prevValue.content
        };
      });
    } else {
      setNote(prevValue => {
        return {
          title: prevValue.title,
          content: value
        };
      });
    }
  }

  return (
    <div>
      <form>
        <input onChange={handleChange} name="title" placeholder="Title" />
        <textarea
          onChange={handleChange}
          name="content"
          placeholder="Take a note..."
          rows="3"
        />
        <button
          onClick={() => {
            props.newNote(note);
          }}
        >
          Add
        </button>
      </form>
    </div>
  );
}

export default CreateArea;

Any help will be greatly appreciated.

Upvotes: 1

Views: 59

Answers (2)

Seth Lutske
Seth Lutske

Reputation: 10686

This is because you are clicking a button in a form. The form is trying to submit, which refreshes the page. You can add e.preventDefault to stop that.

        <button
          onClick={(e) => {
            e.preventDefault()
            props.newNote(note);
          }}
        >

Upvotes: 2

Malik Awan
Malik Awan

Reputation: 463

You need to prevent the default behavior of form submission.

In your OnClick event pass the event as an argument:

<button
      onClick={(e) => {
        props.newNote(e,note);
      }}
    >
      Add
    </button>

and while calling this function on parent component:

function addNote(e,note) {
    e.preventDefault()  // prevent the default behavior
    console.log(note);
  }

Upvotes: 1

Related Questions