Skip to content
Advertisement

How to clear input field after clicking submit in react js redux

I am developing a small project to learn react redux, I had a good view of connecting react with redux. I am trying to perform a small task that is clearing the input box after hitting submit, I’ve tried using reset, wrote separate function to clear the state and included the logic to clear input in handleSubmit handler itself, I didn’t get the expected output. Can anyone guide me how to achieve this. Thanks in advance.

AddRemainder.js File : 

import React, { Component } from "react";
import { connect } from "react-redux";
import addRemainder from "../../redux/action.js";

class AddRemainderPage extends Component {
  state = {
    reminder: {
      title: "",
    },
  };

  handleChange = (e) => {
    const reminder = { ...this.state.reminder, title: e.target.value };
    this.setState({ reminder });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.dispatch(addRemainder(this.state.reminder));
      
  };

  render() {
    return (
      <div className="App">
        <div>
          <h2>My First Redux UnderStanding</h2>
          <form onSubmit={this.handleSubmit}>
            <input
              type="text"
              onChange={this.handleChange}
              value={this.state.reminder.title}
            />

            <input type="submit" value="Save" />
          </form>
        </div>
      </div>
    );
  }
}

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

export default connect(mapStateToProps)(AddRemainderPage);

Action.JS File:

const addRemainder = (text) => ({
  type: "ADD_REMINDER",
  rem: text,
});

export default addRemainder;

Reducer.JS File:

const intialState = {
  reminderss: [],
};

const remindersReducer = (state = intialState, action) => {
  switch (action.type) {
    case "ADD_REMINDER":
      return {
        reminderss: [...state.reminderss, action.rem],
      };
    default:
      return state;
  }
};

export default remindersReducer;

Advertisement

Answer

Try this way:

clearInput = () => {
const reminder = { ...this.state.reminder, title: '' };
this.setState({ reminder });
};

handleSubmit = (e) => {
e.preventDefault();
this.props.dispatch(addRemainder(this.state.reminder));
this.clearInput();
};
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement