Home > Enterprise >  event handler is undefind and it won't recongize -React
event handler is undefind and it won't recongize -React

Time:05-21

I'm learning react and I'm super confused why this event handler is undefind ?

const Login = () => {
  
  handleSubmit = (e) => {
    console.log("Clicked");
    e.preventDefault();
  };

  return (
    <form onSubmit={this.handleSubmit}>
      <input type="email" />
      <input type="password" />
    </form>
  );
};

i get handleSubmit is not defined error and i have no idea why is this happening ?

CodePudding user response:

This seems to be a function component, let alone, using an arrow function. See this question for more details on that.

This means you don’t have access to the keyword “this”, which you’re using on your onSubmit!

CodePudding user response:

i think you have forgot const and you don't need this keyword because you are using function component

const Login = () => {
  
const handleSubmit = (e) => {
    console.log("Clicked");
    e.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" />
      <input type="password" />
    </form>
  );
};

CodePudding user response:

You're mixing up the two different ways to declare a React component.

Choose either:

  1. Class component: which needs to extend the React.Component class, requires the return to be wrapped in render, and does need this to reference the class methods.

const { Component } = React;

class Example extends Component {

  handleSubmit = (e) => {
    e.preventDefault();
    console.log("Clicked");
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="email" />
        <input type="password" />
        <button type="submit">Submit</button>
      </form>
    );
  }

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  1. Function component: which is just a function, doesn't require render, and doesn't require you to reference this to call the handler functions. In addition, function components allow you access to React hooks.

const { Component } = React;

function Example() {

  function handleSubmit(e) {
    e.preventDefault();
    console.log("Clicked");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" />
      <input type="password" />
      <button type="submit">Submit</button>
    </form>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related