1

I have two Buttons in my component. the 'submit note' button refreshes the page (submits the form?) though the function handler for it only says to console.log. The "add note" button does not refresh the page. Both buttons are a part of the form, and both have arrow functions attached to them. Why isn't the "add note" function also refreshing the page? Is it because any component that changes state cannot also submit?

const Button = ({handleClick, text}) => {
  return (
    <button onClick={handleClick}>{text}</button>
    )
  }
export default Button; //component in separate file. added here for clarity


const NoteContainer = () => {
  const [click, setClick] = useState(false)
  const handleClick = () => setClick(true)
  const submitNote = () => console.log('note submitted')

  if (click === true) {
    return (
      <div>
        <Note />
        <Button handleClick={submitNote} text="Submit Note" />
      </div>
    )
  }
  return (
    <div>
      <Button handleClick={handleClick} text='Add Note'/>
    </div>
  )
}

export default NoteContainer;
Vince M
  • 11
  • 2
  • 1
    Is `const submitNote = () => () =>` a typo or do you want it to be a curried function? And by _refreshes the page_ do you mean component re-rendering or an actual refresh on the web page? And I don't see any
    in the code you provided, how does it submit a form?
    – Sinan Yaman Sep 23 '21 at 18:16
  • 1
    Buttons when placed inside a form have `type="submit"` by default, you should explicitly set `type="button"`, however that's also incorrect, see my answer here: https://stackoverflow.com/questions/33211672/how-to-submit-a-form-using-enter-key-in-react-js/33212911#33212911 – Dominic Sep 23 '21 at 18:21
  • @SinanYaman pretend that the components shown are rendered inside a form element. It's a total page refresh, the states of all components are restarted – Vince M Sep 24 '21 at 03:29
  • Don't refresh it. When you refresh your SPA, it would be initialized. – kyun Sep 24 '21 at 03:32

0 Answers0