prevent the user from being able to add names - reactjs

I need to prevent the user from being able to add names that already exist in the person list but I'm not sure where should I add it and also what method is better to use .includes or indexOf? I want issue a warning with the alert command when such an action is attempted. Any help would be much appropriated!
import React, { useState } from 'react'
const App = () => {
const [ persons, setPersons ] = useState([ { name: 'Arto Hellas' }])
const [ newName, setNewName ] = useState('')
const addName = (event) => {
event.preventDefault()
const nameObject = {
name: newName,
}
setPersons([...persons,nameObject])
}
const handleNameChange = (event) => {
setNewName(event.target.value)
}
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={addName} >
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>Numbers</h2>
{persons.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>
)
}
export default App

You need to do something in the following place:
const addName = (event) => {
event.preventDefault();
const nameObject = {
name: newName
};
setPersons([...persons, nameObject]);
};
Use .find() on the persons array to find the particular name already existing and add the condition before setPersons is executed.
if (persons.find(p => p.name === newName)) {
window.alert("Name already exists!");
return false;
}
A code like above will work.
import React, { useState } from "react";
const App = () => {
const [persons, setPersons] = useState([{ name: "Arto Hellas" }]);
const [newName, setNewName] = useState("");
const addName = (event) => {
event.preventDefault();
if (persons.find((p) => p.name === newName)) {
window.alert("Name already exists!");
return false;
}
const nameObject = {
name: newName
};
setPersons([...persons, nameObject]);
};
const handleNameChange = (event) => {
setNewName(event.target.value);
};
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={addName}>
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>Numbers</h2>
{persons.map((person) => (
<p key={person.name}>{person.name}</p>
))}
</div>
);
};
export default App;
Demo: https://codesandbox.io/s/nervous-poitras-i3stw?file=/src/App.js:0-958
The above code shows an ugly Error Alert using the normal window alert. If you want a better error like this:
You can use the following code, by setting a state:
import React, { useState } from "react";
import "./styles.css";
const App = () => {
const [persons, setPersons] = useState([{ name: "Arto Hellas" }]);
const [newName, setNewName] = useState("");
const [error, setError] = useState(false);
const addName = (event) => {
event.preventDefault();
if (persons.find((p) => p.name === newName)) {
setError(true);
return false;
}
const nameObject = {
name: newName
};
setPersons([...persons, nameObject]);
};
const handleNameChange = (event) => {
setNewName(event.target.value);
};
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={addName}>
{error && <p className="error">User already exists.</p>}
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>Numbers</h2>
{persons.map((person) => (
<p key={person.name}>{person.name}</p>
))}
</div>
);
};
export default App;
And here's our style.css:
.error {
background-color: red;
color: #fff;
padding: 5px;
}
Demo: https://codesandbox.io/s/vibrant-tree-wsou2?file=/src/App.js

First add field to check name exists or not:
const nameExists = React.useMemo(() => {
return persons.some(item => item.name === newName);
}, [newName, persons])
Then disable button and show message if name exists:
<div>
{nameExists && <p>Name {newName} already exists!</p>}
<button type="submit" disabled={nameExists} >add</button>
</div>
Also, make sure you clear name when you add new name:
const addName = (event) => {
...
setNewName('')
}
const App = () => {
const [ persons, setPersons ] = React.useState([ { name: 'Arto Hellas' }])
const [ newName, setNewName ] = React.useState('')
const addName = (event) => {
event.preventDefault()
const nameObject = {
name: newName,
}
setPersons([...persons,nameObject]);
setNewName('')
}
const handleNameChange = (event) => {
setNewName(event.target.value)
}
const nameExists = React.useMemo(() => {
return persons.some(item => item.name === newName);
}, [newName, persons])
return (
<div>
<h2>Phonebook</h2>
<form onSubmit={addName} >
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
{nameExists && <p>Name {newName} already exists!</p>}
<button type="submit" disabled={nameExists} >add</button>
</div>
</form>
<h2>Numbers</h2>
{persons.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="root"></div>

You can use the find method to search for a person with the newName. Please check the below code-snippet:
const addName = (event) => {
event.preventDefault()
const nameObject = {
name: newName,
}
let personAlreadyExists = persons.find(person => person.name === newName);
if (personAlreadyExists) {
alert('Person with that name already exists');
// any other operations (like clearing user input in the form, etc..)
}
else {
setPersons([...persons, nameObject])
}
}
Code-Sandbox

Related

How Do I give dynamic colors to the each list here

import React, { useState, useEffect } from "react";
import "./style.css";
const getLocalItem = () => {
let list = localStorage.getItem("lists");
console.log(list);
if (list) {
return JSON.parse(list);
} else {
return [];
}
};
function App() {
const [text, setText] = useState("");
const [task, setTask] = useState(getLocalItem());
const changeText = (e) => {
setText(e.target.value);
};
const submitHandler = (e) => {
console.log("submited");
e.preventDefault();
setTask([...task, text]);
setText("");
};
const removeTask = (a) => {
const finalData = task.filter((curEle, index) => {
return index !== a;
});
setTask(finalData);
};
useEffect(() => {
localStorage.setItem("lists", JSON.stringify(task));
}, [task]);
return (
<>
<form onSubmit={submitHandler} className='form'>
<div className="action" >
<div >
<input
className="input"
type="text"
value={text}
onChange={changeText}
placeholder='add task...'
/>
</div>
<button type="submit" className="button" >
Add todo
</button>
</div>
<div className="listsData">
{task.map((value, index) => {
return (
<>
<div key={index}>
{value}
</div>
</>
);
})}
</div>
</form>
</>
);
}
export default App;
On adding each item I want a different color for each list. Currently, I am fetching list data from localstorage while fetching also it should remain same. which is working but the dynamic colors is what I need for each list. Any ideas or dynamic logics??
Let me know if u need more details regarding my code if u doont understand something

How to manage radio button state with React Typescript?

I am implementing a simple signup page with React Typescript.
I'm trying to set the gender with the radio button, save it in the state, and send it to the server, but the toggle doesn't work.
What should I do?
//RegisterPage.tsx
const [radioState, setradioState] = useState(null);
const [toggle, settoggle] = useState<boolean>(false);
const onRadioChange = (e: any) => {
setradioState(e);
console.log(radioState);
};
const genderOps: ops[] = [
{ view: "man", value: "man" },
{ view: "woman", value: "woman" },
];
<div>
{genderOps.map(({ title, gender }: any) => {
return (
<>
<input
type="radio"
value={gender}
name={gender}
checked={gender === radioState}
onChange={(e) => onRadioChange(gender)}
/>
{title}
</>
);
})}
</div>
You should do some changes on your code, here what you should do:
import React, { EventHandler, useState } from "react";
import "./styles.css";
export default function App() {
const [radioState, setradioState] = useState("");
const [toggle, settoggle] = useState<boolean>(false);
const onRadioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setradioState(e.currentTarget.value);
};
const genderOps = [
{ view: "man", value: "man" },
{ view: "woman", value: "woman" }
];
return (
<div className="App">
<div>
{genderOps.map(({ view: title, value: gender }: any) => {
return (
<>
<input
type="radio"
value={gender}
name={gender}
checked={gender === radioState}
onChange={(e) => onRadioChange(e)}
/>
{title}
</>
);
})}
</div>{" "}
</div>
);
}

How can we get the input text from multiple dynamic textareas in react hook?

I would like to get the text entered in the below input textarea created dynamically after the selection of persons from the dropdown boxes. Would like to get output into a json format:
Now it is getting value from the last displayed text area. Could someone please advise ?
Provide sample codesandbox link below
Expected output:
[
{name:"Bader", reason:"Good news, please add the some data"},
{name:"Crots", reason:"Great person"},
{name:"Dan", reason:"Simple look"}
]
App.js
import React, { useRef, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useHistory } from "react-router-dom";
import Multiselect from "multiselect-react-dropdown";
const options = [
{ key: "Aaron", id: 1 },
{ key: "Bader", id: 2 },
{ key: "Crots", id: 3 },
{ key: "Dan", id: 4 },
{ key: "Elep", id: 5 },
{ key: "Pal", id: 6 },
{ key: "Quilt", id: 7 }
];
const App = () => {
const maxOptions = 3;
const [selectedOption, setSelectedOption] = useState([]);
const [nomRegister, setNomRegister] = useState([]);
const {
register,
handleSubmit,
watch,
formState: { errors }
} = useForm();
const handleTypeSelect = (e) => {
const copy = [...selectedOption];
copy.push(e);
setSelectedOption(copy);
};
const handleTypeRemove = (e) => {
const copy = [...selectedOption];
let index = copy.indexOf(e);
copy.splice(index, 1);
setSelectedOption(copy);
};
const sendNomination = () => {
console.log("Doesn't print all, what the heck: " + nomRegister);
};
return (
<div className="App">
<h1>Person selection</h1>
<div className="nomineeSelectBox">
<div id="dialog2" className="triangle_down1"></div>
<div className="arrowdown">
<Multiselect
onSelect={handleTypeSelect}
onRemove={handleTypeRemove}
options={selectedOption.length + 1 === maxOptions ? [] : options}
displayValue="key"
showCheckbox={true}
emptyRecordMsg={"Maximum nominees selected !"}
/>
</div>
</div>
<form onSubmit={handleSubmit(sendNomination)}>
<div className="nomineesSelectedList">
<h3>Selected Persons</h3>
{selectedOption.map((x, i) => (
<div key={i}>
<div className="row eachrecord">
<div className="column">
<label className="nomlabel">
{x[i].key} <b>>></b>
</label>
</div>
<input
required
type="textarea"
key={i}
id={i}
name={x[i].key}
className="nomineechoosed"
onChange={(e) => setNomRegister(e.target.value)}
/>
</div>
</div>
))}
<div className="row">
<div className="buttongroup">
<input id="Submit" type="submit" value="Submit" />
<input id="Cancel" type="button" value="Cancel" />
</div>
</div>
</div>
</form>
</div>
);
};
export default App;
Codesandbox link:
https://codesandbox.io/s/elastic-elbakyan-uqpzy?file=/src/App.js
After few modifications, I got a solution.
import React, { useRef, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Link, useHistory } from "react-router-dom";
import Multiselect from "multiselect-react-dropdown";
const options = [
{ key: "Aaron", id: 1 },
{ key: "Bader", id: 2 },
{ key: "Crots", id: 3 },
{ key: "Dan", id: 4 },
{ key: "Elep", id: 5 },
{ key: "Pal", id: 6 },
{ key: "Quilt", id: 7 }
];
const App = () => {
const maxOptions = 3;
const [selectedOption, setSelectedOption] = useState([]);
const [nomRegister, setNomRegister] = useState([{}]);
const {
register,
handleSubmit,
watch,
formState: { errors }
} = useForm();
// const onChange = (e) =>{
// e.persist();
// setNomRegister({ ...nomRegister, [e.target.id]: e.target.value });
// }
const handleTypeSelect = (e) => {
const copy = [...selectedOption];
copy.push(e);
setSelectedOption(copy);
};
const handleTypeRemove = (e) => {
const copy = [...selectedOption];
console.log(copy);
let index = copy.indexOf(e);
copy.splice(index, 1);
setSelectedOption(copy);
// immutating state (best practice)
const updateList = nomRegister.map((item) => {
return { ...item };
});
//delete the specific array case depends on the id
updateList.splice(index, 1);
setNomRegister(updateList);
};
const sendNomination = () => {
console.log(
"Doesn't print all, what the heck: " + JSON.stringify(nomRegister) // i did JSON.stringify just to see the console
);
};
const handleChange = (e, i) => {
const { name, value } = e.target;
// immutating state (best practice)
const updateList = nomRegister.map((item) => {
return { ...item };
});
//change the specific array case depends on the id
updateList[i] = { ...updateList[i], name: name, reason: value };
setNomRegister(updateList);
};
return (
<div className="App">
<h1>Person selection</h1>
<div className="nomineeSelectBox">
<div id="dialog2" className="triangle_down1"></div>
<div className="arrowdown">
<Multiselect
onSelect={handleTypeSelect}
onRemove={handleTypeRemove}
options={selectedOption.length + 1 === maxOptions ? [] : options}
displayValue="key"
showCheckbox={true}
emptyRecordMsg={"Maximum nominees selected !"}
/>
</div>
</div>
<form onSubmit={handleSubmit(sendNomination)}>
<div className="nomineesSelectedList">
<h3>Selected Persons</h3>
{selectedOption.map((x, i) => (
<div key={i}>
<div className="row eachrecord">
<div className="column">
<label className="nomlabel">
{x[i].key} <b>>></b>
</label>
</div>
<input
required
type="textarea"
key={i}
id={i}
name={x[i].key}
className="nomineechoosed"
onChange={(e) => handleChange(e, i)}
/>
</div>
</div>
))}
<div className="row">
<div className="buttongroup">
<input id="Submit" type="submit" value="Submit" />
<input id="Cancel" type="button" value="Cancel" />
</div>
</div>
</div>
</form>
</div>
);
};
export default App;
check Codesandbox

I am creating a frontend login form

The stack I am currently using is:
React, React-redux, styled-components, css3
I'm writing a natural responsive login form, and I'm trying to fix it with hooks while watching a course.
constructor(props) {
super(props);
this.state = {
isLogginActive: true
};
}
componentDidMount() {
//Add .right by default
this.rightSide.classList.add("right");
}
changeState() {
const { isLogginActive } = this.state;
if (isLogginActive) {
this.rightSide.classList.remove("right");
this.rightSide.classList.add("left");
} else {
this.rightSide.classList.remove("left");
this.rightSide.classList.add("right");
}
this.setState(prevState => ({ isLogginActive: !prevState.isLogginActive }));
}
render() {
const { isLogginActive } = this.state;
const current = isLogginActive ? "Register" : "Login";
const currentActive = isLogginActive ? "login" : "register";
return (
<div className="App">
<div className="login">
<div className="container" ref={ref => (this.container = ref)}>
{isLogginActive && (
<Login containerRef={ref => (this.current = ref)} />
)}
{!isLogginActive && (
<Register containerRef={ref => (this.current = ref)} />
)}
</div>
<RightSide
current={current}
currentActive={currentActive}
containerRef={ref => (this.rightSide = ref)}
onClick={this.changeState.bind(this)}
/>
</div>
</div>
);
}
}
const RightSide = props => {
return (
<div
className="right-side"
ref={props.containerRef}
onClick={props.onClick}
>
<div className="inner-container">
<div className="text">{props.current}</div>
</div>
</div>
);
};
export default App;
I'm working on the code from the lecture with hooks, but I'm starting to get confused about how to write a ref in the DOM.
export default function Modal() {
const dispatch = useDispatch();
const { isModal } = useSelector((state) => state.modal_Reducer);
const mainRef = useRef();
const rightRef = useRef();
const [isActive, setIsActive] = useState(true);
useEffect(() => {
rightRef.classList.add("right");
}, []);
const changeAuth = () => {
if (isActive) {
rightRef.classList.remove("right");
rightRef.classList.add("left");
} else {
rightRef.classList.remove("left");
rightRef.classList.add("rignt");
}
setIsActive(!isActive);
};
const onHideModal = () => {
dispatch(hideModal());
};
if (!isModal) {
return null;
}
const switchToSignup = isActive ? "Register" : "Login";
const switchToSignin = isActive ? "Login" : "Register";
return (
<ModalBackground>
<Main_Container>
<Auth_box ref={mainRef}>
{}
{}
</Auth_box>
<RightSide
ref={rightRef}
switchLogin={switchToSignin}
switcReg={switchToSignup}
onClick
/>
</Main_Container>
</ModalBackground>
It is a modal component that converts to the signup form while css animation effect occurs when the signup button is pressed in the login form.
I used useRef, but I think it's not right to use classList.add and .remove, so I need to fix it, but I'm not sure how to do it. Help.
useEffect(() => {
//rightRef.classList.add("right");
}, []);
const changeAuth = () => {
/* if (isActive) {
rightRef.classList.remove("right");
rightRef.classList.add("left");
} else {
rightRef.classList.remove("left");
rightRef.classList.add("rignt");
}
*/
setIsActive(!isActive);
};
and then
<RightSide
clsName={isActive? "right":"left"}
switchLogin={switchToSignin}
switcReg={switchToSignup}
onClick
/>
and update your component
const RightSide = props => {
return (
<div
className={`right-side ${props.clsName}`}
onClick={props.onClick}
>
<div className="inner-container">
<div className="text">{props.current}</div>
</div>
</div>
);
};
You can also explore https://www.npmjs.com/package/classnames npm package
useEffect(() => {
//rightRef.classList.add("right");
}, []);
const changeAuth = () => {
/* if (isActive) {
rightRef.classList.remove("right");
rightRef.classList.add("left");
} else {
rightRef.classList.remove("left");
rightRef.classList.add("rignt");
}
*/
setIsActive(!isActive);
};
and then
<RightSide
clsName={isActive? "right":"left"}
switchLogin={switchToSignin}
switcReg={switchToSignup}
onClick
/>
First, I set up a frame and kept working.
export default function Modal() {
const dispatch = useDispatch();
const { isModal } = useSelector((state) => state.modal_Reducer);
const mainRef = useRef();
const authRef = useRef();
const [isActive, setIsActive] = useState(true);
useEffect(() => {}, []);
const changeAuth = () => {
if (isActive) {
} else {
}
setIsActive(!isActive);
};
const onHideModal = () => {
dispatch(hideModal());
};
if (!isModal) {
return null;
}
const switchToSignup = isActive ? "Register" : "Login";
const switchToSignin = isActive ? "Login" : "Register";
return (
<ModalBackground>
<Main_Container ref={mainRef}>
<Auth_box>
{isActive && <Login authRef={authRef} />}
{!isActive && <Register authRef={authRef} />}
</Auth_box>
</Main_Container>
<RightSide
onSwitch={isActive ? "right" : "left"}
switchSignIn={switchToSignin}
switchRegister={switchToSignup}
onClick={changeAuth}
/>
</ModalBackground>
);
}
function RightSide(props) {
return (
<Right_Side
className={`right-side ${props.onSwitch}`}
ref={props.mainRef}
onClick={props.changeAuth}
>
<div className="inner-container">
<div className="text">{props.switchRegister}</div>
</div>
</Right_Side>
);
}
The problem is the login form conversion page, but the original uses ref and passes it as props.
login and register transfer current as ref.
But I don't understand why the container passes this.container.
original
export class Login extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="base-container" ref={this.props.containerRef}>
<div className="header">Login</div>
<div className="content">
<div className="image">
<img src={loginImg} />
</div>
<div className="form">
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" name="username" placeholder="username" />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" name="password" placeholder="password" />
</div>
</div>
</div>
<div className="footer">
<button type="button" className="btn">
Login
</button>
</div>
</div>
);
}
my code
function Login(props) {
const dispatch = useDispatch();
const history = useHistory();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [submited, setSubmited] = useState(false);
const [showPwd, setShowPwd] = useState(false);
const [alert, setAlert] = useState("");
const formInputValue = (key) => (e) => {
if (key === "EMAIL") setEmail(e.target.value);
if (key === "PASSWORD") setPassword(e.target.value);
console.log(e.target.value);
};
const onLogin = async (e) => {
e.preventDefault();
if (!email || !password) {
setAlert("이메일 주소와 비밀번호를 입력 하세요!");
}
let data = {
email: email,
password: password,
};
dispatch(loggedIn(data));
history.push("/");
};
return (
<PanelContainer ref={props.authRef}>
<h1>로그인</h1>
<PanelContent>
<Form onSubmit={onLogin}>
<InputGroup>
<label htmlFor="email">E-Mail</label>
<Input
type="text"
name="email"
value={email}
onChange={formInputValue("EMAIL")}
placeholder="E-mail"
/>
</InputGroup>
<InputGroup>
<label htmlFor="password">Password</label>
<Input
type={showPwd ? "text" : "password"}
name="password"
value={password}
onChange={formInputValue("PASSWORD")}
placeholder="Password"
/>
</InputGroup>
<SubmitBtn> 로그인 </SubmitBtn>
</Form>
</PanelContent>
</PanelContainer>
);
}
export default Login;

getting error 'TypeError: newData is not iterable'

I am trying to add the objects into the localstorage by the use of state but not able to get the desired results as i want to save the username,password,firstname,last name into the localstorage and also display these elements of object into the HomePage and getting error 'TypeError: newData is not iterable'....Any help will be much appreciated.
App.js
import LoginForm from "./Component/LoginForm/LoginForm";
import HomePage from "./Component/HomePage/HomePage";
import { useState, useEffect } from "react";
const user = [];
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userData,setUserData] = useState(user);
console.log('userData: ',userData);
localStorage.setItem('CompleteData',JSON.stringify(userData));
const getObj = JSON.parse(localStorage.getItem('CompleteData'));
console.log('getObj: ',getObj);
useEffect(() => {
const isUserLoggedIn = localStorage.getItem("isLoggedInn");
if (isUserLoggedIn === "1") {
setIsLoggedIn(true);
}
}, []);
const loginHandler = (username,first,last,pass) => {
localStorage.setItem("isLoggedInn", "1");
setIsLoggedIn(true);
localStorage.setItem('currentUsername',username);
localStorage.setItem('currentFirstname',first);
localStorage.setItem('currentLastname',last);
localStorage.setItem('currentPassword',pass);
};
const logoutHandler = () => {
localStorage.removeItem("isLoggedInn");
setIsLoggedIn(false);
};
const onSaveDataHandler = (newData) => {
setUserData((prevData)=>{
return [prevData,...newData];
});
};
const dataFormHandler = (username, first,last,pass) => {
return [
localStorage.getItem('currentUsername'),
localStorage.getItem('currentFirstname'),
localStorage.getItem('currentLastname'),
localStorage.getItem('currentPassword')
];
}
return (
<>
<div>
{!isLoggedIn && (
<LoginForm
onLogin={loginHandler}
onSaveData={onSaveDataHandler}
usersD={getObj}
/>
)}
{isLoggedIn && (
<HomePage onLogout={logoutHandler} user={dataFormHandler()} />
)}
</div>
</>
);
}
export default App;
import styles from "./LoginForm.module.css";
import { useState } from "react";
import SignUp from "../SignUp/SignUp";
const LoginForm = (props) => {
const [enteredUsername, setEnteredUsername] = useState("");
const [enteredPassword, setEnteredPassword] = useState("");
const [isTrue, setTrue] = useState(true);
const [isClicked, setIsClicked] = useState(false);
const onChangeHandlerUsername = (event) => {
setEnteredUsername(event.target.value);
if (event.target.value === enteredUsername) {
setTrue(true);
}
};
const onChangeHandlerPassword = (event) => {
setEnteredPassword(event.target.value);
if (event.target.value === enteredPassword) {
setTrue(true);
}
};
const onSubmitHandler = (event) => {
event.preventDefault();
props.usersD.forEach((element,i)=>{
if (
enteredUsername === element[i].username &&
enteredPassword === element[i].password
){
props.onLogin(element[i].username,element[i].firstname,element[i].lastname,element[i].password);
}
else {
setTrue(false);
};
})
};
const onClickHandler = () => {
setIsClicked(true);
};
const sendDataToChild = (entereduserData) =>{
const userData = {
id: Math.random().toString(),
...entereduserData
};
props.onSaveData(userData);
}
return (
<>
{isClicked &&
enteredUsername !== Object.keys(props.usersD).username &&
enteredPassword !== Object.keys(props.usersD).password ? (
<SignUp dataTransfer={sendDataToChild} clk={setIsClicked}/>
) : (
<form onSubmit={onSubmitHandler}>
<h1 className={styles.blink_me}>W E L C O M E</h1>
<div className={`${styles.box} ${!isTrue && styles.wrong}`}>
<h1>Login</h1>
<input
type="text"
value={enteredUsername}
placeholder="Enter Username"
className={styles.email}
onChange={onChangeHandlerUsername}
></input>
<input
type="password"
value={enteredPassword}
placeholder="Enter Password"
className={styles.email}
onChange={onChangeHandlerPassword}
></input>
<div>
<button className={styles.btn}>Sign In</button>
</div>
<div>
<button
onClick={onClickHandler}
type="button"
className={styles.btn2}
>
Sign Up
</button>
</div>
<div>
Forget Password
</div>
</div>
</form>
)}
</>
);
};
export default LoginForm;
HomePage.js
import styler from './HomePage.module.css';
const HomePage = (props) =>{
const name = props.user[0];
const first = props.user[1];
const last = props.user[2];
const pass = props.user[3];
return(
<>
<div className={styler.body}>
<h2>Login Successfull !</h2>
{/* {props.user.map(users=><p username={users[0]} password={users[1]}/>)} */}
<p>Name: {name}</p>
<p>FirstName: {first}</p>
<p>LastName: {last}</p>
<p>Password: {pass}</p>
<button type='submit' onClick={props.onLogout} className={styler.button}>Logout</button>
</div>
</>
);
}
export default HomePage;

Resources