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 ?
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>
);
};
You're mixing up the two different ways to declare a React component.
Choose either:
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>
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>