I am working on my first React program, it is the one provided by Sololearn (Contact Manager). I am trying to add a function to search for a contact: SearchName. However, I need to click many times on the Search button for it to work. Can someone please tell me where I went wrong? For example, typing James Smith in the enter a name to search field first gives "is not in list". Then when clicked again, it updates to is in list.
Here is the code:
import React, { useState } from "react";
import ReactDOM from "react-dom";
function AddPersonForm(props) {
const [person, setPerson] = useState("");
function handleChange(e) {
setPerson(e.target.value);
}
function handleSubmit(e) {
if (person !== "") {
props.handleSubmit(person);
setPerson("");
}
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add new contact"
onChange={handleChange}
value={person}
/>
<button type="submit">Add</button>
</form>
);
}
function RemovePersonForm(props) {
const [person, setPerson] = useState("");
function handleChange(e) {
setPerson(e.target.value);
}
function handleSubmit(e) {
props.handleSubmit(person);
setPerson("");
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="enter name to delete"
onChange={handleChange}
/>
<button type="submit">Delete</button>
</form>
);
}
function PeopleList(props) {
const arr = props.data;
const listItems = arr.map((val, index) => <li key={index}>{val}</li>);
return <ul>{listItems}</ul>;
}
function SearchName(props) {
const [contacts, setContacts] = useState(props.data);
const [person, setPerson] = useState("");
const [isInList, setIsInList] = useState(false);
const [text, setText] = useState("");
function handleChange(e) {
setPerson(e.target.value);
}
function handleSubmit(e) {
setIsInList(false);
for (var c of contacts) {
if (c == person) {
setIsInList(true);
break;
}
}
if (isInList) {
setText("is in list");
} else {
setText("is not in list");
}
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="enter name to search"
onChange={handleChange}
/>
<button type="sumbit">Search</button>
<p>{text}</p>
</form>
);
}
function ContactManager(props) {
const [contacts, setContacts] = useState(props.data);
function addPerson(name) {
setContacts([...contacts, name]);
}
function removePerson(name) {
var newContacts = new Array();
var i = 0;
for (var c of contacts) {
if (c != name) {
newContacts[i] = c;
i++;
}
}
setContacts(newContacts);
}
return (
<div>
<AddPersonForm handleSubmit={addPerson} />
<RemovePersonForm handleSubmit={removePerson} />
<SearchName data={contacts} />
<PeopleList data={contacts} />
</div>
);
}
const contacts = ["James Smith", "Thomas Anderson", "Bruce Wayne"];
ReactDOM.render(
<ContactManager data={contacts} />,
document.getElementById("root"),
);