Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor addContact from class component to functional component #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 37 additions & 41 deletions src/components/AddContact.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,46 @@
import React from "react";
import React, { useState } from "react";

class AddContact extends React.Component {
state = {
name: "",
email: "",
};
const AddContact = ({ addContactHandler }) => {
const [state, setState] = useState({ name: "", email: "" });

add = (e) => {
const add = (e) => {
e.preventDefault();
if (this.state.name === "" || this.state.email === "") {
if (state.name === "" || state.email === "") {
alert("ALl the fields are mandatory!");
return;
}
this.props.addContactHandler(this.state);
this.setState({ name: "", email: "" });
addContactHandler(state);
setState({ name: "", email: "" });
};
render() {
return (
<div className="ui main">
<h2>Add Contact</h2>
<form className="ui form" onSubmit={this.add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<button className="ui button blue">Add</button>
</form>
</div>
);
}
}

return (
<div className="ui main">
<h2>Add Contact</h2>
<form className="ui form" onSubmit={add}>
<div className="field">
<label>Name</label>
<input
type="text"
name="name"
placeholder="Name"
value={state.name}
onChange={(e) => setState({ name: e.target.value })}
/>
</div>
<div className="field">
<label>Email</label>
<input
type="text"
name="email"
placeholder="Email"
value={state.email}
onChange={(e) => setState({ email: e.target.value })}
/>
</div>
<button className="ui button blue">Add</button>
</form>
</div>
);
};

export default AddContact;