Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass down input value during onSubmit in React?

Tags:

forms

reactjs

I have a basic form in React that asks for username. After entering desired username (say iggy), I want it to console.log that username, iggy.

Here is the thing: traditionally, I would do something like

constructor(){
  super();
  this.state={username: ''}
  ...

  handleUsernameEnter: function(e){
    this.setState({
      username: e.target.value
    })
  },
  ...
  <form onSubmit={this.handleUsernameSubmission}>
    <input placeholder="enter username" ref="usernameItem" onChange={this.handleUsernameEnter} />
    <input type="submit" value="Submit username" />
  </form>
  ...

I would store username in state as user inputs it. No problem. This time, I don't want to save username in state yet. I want user to enter username on the input text, when user clicks submit button, handleUsernameSubmission would somehow get the value of the username that the user enters, and console.log that value. I couldn't figure out how to pass the value from input to username variable in handleUsernameSubmission.

handleUsernameSubmission: function(username){
    console.log('username entered: ', username)
  },

JSFiddle: https://jsfiddle.net/iggyfiddle/adj4Ln1p/3/

How can I get the username to be passed down from form's input value to username variable in handleUserSubmission without saving it to state first?

My gut feeling says I need to use ref in the input, but I am not sure how to reference the onsubmit to get the value from that particular input. Something like <form onSubmit={this.handleUsernameSubmission(input.'usernameItem')}>

like image 313
Iggy Avatar asked Mar 20 '17 20:03

Iggy


People also ask

What is Handleinputchange in React?

The handleChange() function that you see in many React component examples is a regular function created to handle input change. It's commonly passed into an <input> element's onChange property to intercept user's input.

How do you prevent a form from clearing fields on submit React?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.

How to use react to set the value of an input?

How to Use React to Set the Value of an Input 1 Introduction. React apps have a form element, which is slightly different from the HTML form as it maintains its internal state for the values. 2 Controlled Input Approach. ... 3 Uncontrolled Input Approach. ... 4 Conclusion. ...

What is a controlled form input in react?

Form controls in React are a bit different from the standard HTML form controls because each input element in a React form manages the internal state behind the scene. Using a controlled form input approach, you can maintain the state values as an input for the various form controls. For that, you need to maintain a state like this:

How to use onsubmit event in react functional components?

Use onSubmit Event in React Functional Components 1 Create ReactJS Project 2 Create New Component 3 Add Component to Entry File 4 Structure of Project 5 Run Application 6 Output 7 Output on Console Log

How do I reference an element in react onsubmit?

Using the React.useRef () hook, we can reference an element easily. For example, to be able to reference " email " and " age " input fields in the onSubmit handler, we can do something like the following: The current property of the reference object holds the actual reference to the element.


2 Answers

You also can use event object.

So your submit will look like that in this case.

class Form extends React.Component {

  handleSubmit = (e) => {
    if(e) e.preventDefault();
    const [input] = e.target.children
    console.log('Your name is', input.value);
  }

  render(){
     return (
      <form onSubmit={this.handleSubmit}>
        <input placeholder="Your name" type="text"/>
        <button>Submit!</button>
      </form>
    )
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

So you basically get DOMElement of form using e.target then you also access its children DOMElements and using array spread ES6 feature, you take the first one, which is your input then you use its value, in your console.log call.

Without ES6 spread it will look like.

  handleSubmit = (e) => {
    if(e) e.preventDefault();
    const input = e.target.children[0]
    console.log('Your name is', input.value);
  }

Of course, it's usually better to use refs but when you really have that simple example, you can do it this way. But in a real app, I wouldn't rely on elements order etc.

like image 44
Andrii Los Avatar answered Nov 15 '22 21:11

Andrii Los


Yes, you can use this.refs here of course.

Please have a look at the documentation.

Here is the code:

var Hello = React.createClass({

  handleUsernameSubmission: function(e){
    if(e) e.preventDefault();
    const name = this.refs.usernameItem.value;
    console.log('Your name is', name);
  },

  render: function() {
    return (
      <div>
        <form onSubmit={this.handleUsernameSubmission}>
          <input placeholder="enter username" ref="usernameItem" />
          <input type="submit" value="Submit username" />
        </form>
      </div>
    )
  }
});


ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Also, I've implemented ES6 version of it, it looks better:

class Form extends React.Component {

  handleSubmit = (e) => {
    if(e) e.preventDefault();
    const name = this.input.value;
    console.log('Your name is', name);
  }

  render(){
     return (
      <form onSubmit={this.handleSubmit}>
        <input placeholder="Your name" type="text" ref={(element) => { this.input = element }} />
        <button>Submit!</button>
      </form>
    )
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument. React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts.

Using the ref callback just to set a property on the class is a common pattern for accessing DOM elements. The preferred way is to set the property in the ref callback like in the above example.

like image 68
Dan Cantir Avatar answered Nov 15 '22 19:11

Dan Cantir