staxwell staxwell - 11 days ago 8
Javascript Question

Is there a good way to preventDefault when dispatching an action in React/Redux?

I'm dispatching an action that runs a reducer that pushes some text to my redux state on form submit. I know in Vue you can

preventDefault
right in the DOM but I haven't seen anything in React that would make this seem possible.

I'm wondering the best way to prevent the form from submitting so Redux can do it's thing. My code is below. Thanks!

actions/index.js

export function addLink(text) {
return {
type: 'ADD_LINK',
text
}
}


reducers/index.js (ADD_LINK) is the function I'm running

/*eslint-disable*/
export function linkList(state = [], action) {
switch(action.type) {
case 'ADD_LINK':
var text = action.text;
console.log('Adding link');
console.log(text);
return {
...state,
links: [text, ...state.links]
};
case 'DELETE_LINK':
var index = action.index;
console.log('Deleting link');
return {
...state,
links: [
...state.links.slice(0, index),
...state.links.slice(index + 1)
],
};
case 'UPDATE_LINK':
var index = action.index;
var newText = action.newText;
console.log(action.newText);
console.log(action.index);
return {
...state,
links: [
...state.links.slice(0, index),
newText,
...state.links.slice(index + 1)
],
}
default:
return state;
}
};

export default linkList;


components/LinkInput.js (Here is where I dispatch the action onSubmit)

import React, { Component } from 'react';

class LinkInput extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
};
}
handleChange(e) {
e.preventDefault();
this.setState({
text: e.target.value
});
}
render() {
return (
<form className="form form-inline" onSubmit={this.props.data.addLink.bind(null, this.state.text)} style={styles.form}>
<div className="form-group">
<label className="label" htmlFor="exampleInputName2" style={styles.label}>Add a link: </label>
<input type="text" className="input form-control" onChange={this.handleChange.bind(this)} style={styles.input}/>
</div>
<button type="submit" className="button btn btn-primary" style={styles.button}>Add link</button>
</form>
);
}
}


export default LinkInput;

Answer

What i would do is define a function in your component called _onSubmit and have it do like so:

_onSubmit(e) {
  e.preventDefault();
  this.props.data.addLink(this.state.text)
}

and then your form component just uses this._onSubmit for its onSubmit handler

<form className="form form-inline" onSubmit={this._onSubmit} style={styles.form}>

this will handle the event and dispatch the correct action.