0

I have a component with an input that when submitted is meant to pass the input text to store. I can't figure out how to preventDefault() when I submit the form.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addItem } from '../actions';

const ItemInput = (props) => {
  return (
    <div>
      <form onSubmit={() => props.addItem('test')}>
        <input 
          placeholder="addItem"
        />
      </form>
    </div>
  );
}

const mapStateToProps = (state) => {
  return { addItem: state.addItem };
}

export default connect(mapStateToProps, {
  addItem: addItem
})(ItemInput);

I know how to do this in react, but it doesn't seem to work the same way, I keep getting an unexpected token error that doesn't make any sense, probably because the syntax just doesn't work the same way with redux and store. This also isn't a button issue, I'm submitting the form after pressing return.

Matt Brody
  • 1,473
  • 3
  • 14
  • 23
  • 1
    Possible duplicate of [React - Preventing Form Submission](https://stackoverflow.com/questions/39809943/react-preventing-form-submission) – Frondor Mar 25 '19 at 05:11

1 Answers1

3

This part of your code is just a function, you can expand it as you want:

<form onSubmit={() => props.addItem('test')}>

So, you can do:

<form onSubmit={e => {
  e.preventDefault();
  props.addItem('test');
}}>

Or move this handler into a function:

const handleSubmit = e => {
  e.preventDefault();
  props.addItem('test');
}

// ... 

<form onSubmit={handleSubmit}>
rrk
  • 15,677
  • 4
  • 29
  • 45
flppv
  • 4,111
  • 5
  • 35
  • 54