oosniss oosniss - 4 months ago 80
Javascript Question

How to pass in a second argument on ReactJS onSubmit function call

Here are the codes

import React from "react";

var newForm = React.createClass({
handleSubmit: function (e, text) {
e.preventDefault();
console.log(text);
},
render: function () {
return (
<form onSubmit={this.handleSubmit("react!!!")}>
<input type="text"/>
</form>
);
}
)};

module.exports = newForm;


What I want to achieve with this is that when I submit the form, I want the string "react!!!" to be printed out in the console and prevent the default event from taking place at the same time.

Obviously, passing in the argument to "handleSubmit" function breaks the code.

Is there anyway to pass in an argument from onSubmit event to the functions attached to this event?

Answer

You can curry the function

handleSubmit: text => event => {
  event.preventDefault()
  console.log(text)
}

<form onSubmit={this.handleSubmit('react!!!')}>
  ...

Equivalent ES5 code

handleSubmit: function(text) {
  return function(event) {
    event.preventDefault()
    console.log(text)
  }.bind(this)
}

Your code is weird though because you're mixing ES6 and ES5 styles. If you're using ES6 imports, you might as well use ES6 in the rest of your code

import {Component} from 'react'

class NewForm extends Component {
  handleSubmit (text) {
    return event => {
      event.preventDefault()
      console.log(text)
    }
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit('react!!!')}>
        <input type="text">
      </form>
    }
  }
}

export default NewForm

Or better, since your Component doesn't use any state, you can use a Stateless Functional Component

import {Component} from 'react'

const handleSubmit = text=> event=> {
  event.preventDefault()
  console.log(text)
}

const NewForm = props=> (
  <form onSubmit={handleSubmit('react!!!')}>
    <input type="text">
  </form>
)

export default NewForm