← react hacks / react / preventing-default-actions-in-event-handlers.md

Preventing Default Actions in Event Handlers

Learn how to prevent default actions in event handlers in React. It includes snippets of code to easily understand and implement this approach.

In React, browser-based events often come with default behaviors. For instance, a form submission reloads the page by default. To prevent this, we can use the event.preventDefault() method.

Consider a form submission event:

class Form extends React.Component {
  handleSubmit(event) {
    event.preventDefault();
    // handle logic here
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <button type="submit">Submit</button>
      </form>
    )
  }
}

In the example above, event.preventDefault() stops the default browser behavior of reloading the page on form submission. Instead, the handleSubmit function is executed.

Remember, not all event handlers have default actions. For those that do, event.preventDefault() can be a useful tool to control the behavior of your React app.


Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  2. 8150376 Adding Event Handlers in JSX

    tag: reacttag: jsxtag: event handlers

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?