Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React use outside functions as methods

I have some functions that I need to use in several components so I put them in a module like this.

export default class FormFunctions {
  handleChange (event) {
    const changedOne = event.target.name
    const newValue = event.target.value
    const newState = {}
    newState[changedOne] = newValue
    this.setState(newState)
  }
  handleSubmit (infoToPass, toThisMethod) {
    Meteor.call(toThisMethod, infoToPass, function () {
      console.log('userCreate call callback')
    })
  }
}

How can I use them as methods for my components?

I tried it like this but it doesn't work. And well I am not sure if I need any classes at all.

import React, { Component } from 'react'
import Register from './Register.jsx'
import FormFunctions from './FormFunctions'

class RegisterLogic extends Component {

  render () {
    return <Register
      handleChange={this.handleChange}
      handleSubmit={this.handleSubmit}
      />
  }
}

export default RegisterLogic
like image 614
Hayk Safaryan Avatar asked Aug 09 '26 04:08

Hayk Safaryan


1 Answers

You can make this work by making two small changes to your code:

  1. Instead of this.handleChange, you will have to use FormFunctions.handleChange . To be able to refer the function from the class, you can add static to its definition: static handleChange (event) { or create and use an object of the class.

  2. For whatever reason, you call a .bind(this) to tell react components which function to use for something, so your code becomes handleChange={FormFunctions.handleChange.bind(this)} .

Hope this helps.

like image 186
Akshay Jain Avatar answered Aug 11 '26 17:08

Akshay Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!