0

i got a problem in making my local variable to be accessible outside the class

class LoginForm extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {

    const {
      handleSubmit,
      pristine,
      reset,
      submitting,
      submitData,
      renderTextField,
      validation
    } = this.props;

    return (
      <Card className="container">
        <form onSubmit={handleSubmit(submitData)}>
          <h2 className="card-heading">Login</h2>

          <div className="field-line">
            <Field name="email" component={renderTextField} label="Email"/>
          </div>
        </form>
      </Card>
    )
  }
};
LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);

export default LoginForm

i want to make validation available in

LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);

ukiyakimura
  • 151
  • 1
  • 5
  • 15

2 Answers2

0

Global variables, for purposes such as this, are generally discouraged. The reasons are very well detailed in other answers, such as per this answer:

The primary reason why global variables are discouraged in javascript is because, in javascript all code share a single global namespace, also javascript has implied global variables ie. variables which are not explicitly declared in local scope are automatically added to global namespace. Relying too much on global variables can result in collisions between various scripts on the same page.

Instead of passing the validation (function?) down as a prop, perhaps consider refactoring it into a helper file and then importing it into your form.

Example:

//helpers.js

const validation = (someParams) => {
  return (
    // do validation here as required
  );
}

export default validation;

and

// LoginForm.js

import { validation } from './path/to/helpers';

...

LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);
...
Community
  • 1
  • 1
patrick
  • 9,837
  • 3
  • 20
  • 27
-1

To make a global class variable (not advised) do something like this:

let my_global = 0;

class LoginForm extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {

    const {
      handleSubmit,
      pristine,
      reset,
      submitting,
      submitData,
      renderTextField,
      validation
    } = this.props;
    console.log(my_global); #we can access the global variable anywhere in here
    return (
      <Card className="container">
        <form onSubmit={handleSubmit(submitData)}>
          <h2 className="card-heading">Login</h2>

          <div className="field-line">
            <Field name="email" component={renderTextField} label="Email"/>
          </div>
        </form>
      </Card>
    )
  }
};
LoginForm = reduxForm({form: 'LoginForm', validation})(LoginForm);

export default LoginForm
Turtle
  • 1,369
  • 1
  • 17
  • 32