tarek hassan
tarek hassan

Reputation: 802

How should I pass input value with Redux without using this.state and setState

As I am learning Redux, I managed to use Provider, use child component, connect them etc.

But I have form in child component, I want to pass data from child to parent but on Submit. I don't want to use 'value onChange setState value' method. I want to use Redux with this.

I can also think of doing onChange dispatch but I want to pass values once onSubmit happens only.

import React from "react";

class InputComponent extends React.Component {
  addNewTodo = (e) => {
    e.preventDefault()
    console.log(e.target);
  };

  render() {
    return (
      <form onSubmit={this.addNewTodo}>
        <input
          type="text"
          class="form-control form-control-lg addTodoform"
          id='addTodoform'
          placeholder="Add new task or note"
          defaultValue=''
        />
        <button type="submit" class='btn btn-primary' >
          Add
        </button>
      </form>
    );
  }
}

export default InputComponent;

Upvotes: 0

Views: 63

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

One way to achieve what you want would be to use the document API to access the value of the form input addTodoform like so:

const inputValue = document.getElementById('addTodoform').value;

So, in your addNewTodo() handler, you might do the following:

class InputComponent extends React.Component {
  addNewTodo = (e) => {
    e.preventDefault()
    console.log(e.target);

    // Get value from input directly, without the use of setState, etc
    const inputValue = document.getElementById('addTodoform').value;

    // Dispatch inputValue to your redux action
    // dispatch(submitAction(inputValue))
  };

  render() {
    return (
      <form onSubmit={this.addNewTodo}>
        <input
          type="text"
          class="form-control form-control-lg addTodoform"
          id='addTodoform'
          placeholder="Add new task or note"
          defaultValue=''
        />
        <button type="submit" class='btn btn-primary' >
          Add
        </button>
      </form>
    );
  }
}

Hope this helps

Upvotes: 1

Related Questions