How to give props from one page to another with react Router - javascript

I have a problem: I have two pages, one named /login and the other one is called /app.
My problem is that I don't know how to pass props from /login to /app. In /app I want to show the person who logged in a welcome message with his name like: "Welcome Kazim". Hope you guys can help me. There is no problem to link from /login to /app but the props won't get passed.
import React, { useState } from "react";
import { Link, useHistory } from 'react-router-dom';
import axios from 'axios';
import "./SignIn.css";
import Logo from '../../images/logo.PNG';
function SignIn() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [validationWrong, setValidationWrong] = useState(true);
//eslint-disable-next-line
const [validationNoExist, setValidationNoExist] = useState(true);
const history = useHistory();
const test2 = {
pathname: '/app',
state: { email: 'irgendwas#web.de',
name: "horst" }
};
/* Wird an das Backend geschickt und wir erhalten eine Antwort */
const handleLogin = () => {
axios.post('https://localhost.../', {"email":email, "password":password})
.then(res => {
console.log(res);
console.log(res.data);
console.log(res.status);
if(res.status === 200) {
console.log("Willkommen")
setValidationWrong(true);
setValidationNoExist(true);
history.push(test2)
}
else if(res.status === 203) {
setValidationWrong(false);
}
else if(res.status === 204) {
setValidationNoExist(false);
}
})
.catch(error => {
console.log(error)
setValidationNoExist(false);
})
};
//const handleLogin2 = useCallback(() => {history.push('/sample')}, [history]);
return (
<div className="SignIn">
<div className="container" id="container">
<div className="form-container sign-in-container">
<form>
<div className="Logo"><img src={Logo} alt="Logo" /></div>
<h2>Entdecke neue Freunde</h2>
<input type="email" className={(validationWrong && validationNoExist) ? 'input-form' : 'input-form-validation-wrong'} onChange={event => setEmail(event.target.value)} placeholder="E-Mail" />
<input type="password" id="password" className={(validationWrong && validationNoExist) ? 'input-form' : 'input-form-validation-wrong'} onChange={event => setPassword(event.target.value)} placeholder="Passwort" />
{validationWrong === false &&
<p className='validation-wrong'>E-Mail oder Passwort ist falsch</p>
}
{validationNoExist === false &&
<p className='validation-wrong'>Diese E-Mail existiert nicht</p>
}
<div className='optional-buttons'>
<input id="input-remain" type="checkbox" className="input-remain" /><label for="input-remain">Angemeldet bleiben</label>
<a className="password-forgot" href="/">Passwort vergessen?</a>
</div>
<div className='buttons-container'>
<Link>
<button className="button-login" type="button" onClick={handleLogin}>Anmelden</button>
</Link>
<Link to="/registrieren" >
<button className="button-registration" type="button">Registrieren</button>
</Link>
</div>
</form>
</div>
<div className="overlay-container">
<div className="overlay">
<div className="overlay-panel overlay-right">
</div>
</div>
</div>
</div>
</div>
);
}
export default SignIn;
Here is the Chat.js
import React from "react";
import '../components/testchat/Testchat'
import Testchat from "../components/testchat/Testchat";
function Chat(props) {
return (
<div>
<h1>Willkommen {props.name}</h1>
<Testchat></Testchat>
</div>
);
}

Given route push with state:
history.push({
pathname: '/app',
state: {
email: 'irgendwas#web.de',
name: "horst",
},
})
You can access the route state on the location object on the receiving route. You can access the location object via the useLocation React hook.
function Chat(props) {
const { state } = useLocation();
const { name } = state;
return (
<div>
<h1>Willkommen {name}</h1>
<Testchat></Testchat>
</div>
);
}

Related

How to display User name in profile page - react / firebase

I have made a signup/login/logout page which works perfectly fine, however I wanted to add an additional field in the register page for user name, and I wanted the username to display in the profile page.
I was able to inset the username field into the register page, and I have a name section on the profile page which also shows up when the profile page loads, however, when I input a user name in the register page, it does not appear in the profile page.
Can anyone please help me figure this out? I really appreciate the help everyone. My first post here :) just recently started my developer journey
// register.js
import { useState } from "react";
import "./forms.css";
import { auth } from "./firebase";
import { useNavigate, Link } from "react-router-dom";
import {
createUserWithEmailAndPassword,
sendEmailVerification,
} from "firebase/auth";
import { useAuthValue } from "./AuthContext";
function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState("");
const navigate = useNavigate();
const { setTimeActive } = useAuthValue();
const validatePassword = () => {
let isValid = true;
if (password !== "" && confirmPassword !== "") {
if (password !== confirmPassword) {
isValid = false;
setError("Passwords does not match");
}
}
return isValid;
};
const register = (e) => {
e.preventDefault();
setError("");
if (validatePassword()) {
// Create a new user with email and password using firebase
createUserWithEmailAndPassword(auth, email, password)
.then(() => {
sendEmailVerification(auth.currentUser)
.then(() => {
setTimeActive(true);
navigate("/verify-email");
})
.catch((err) => alert(err.message));
})
.catch((err) => setError(err.message));
}
setName("");
setEmail("");
setPassword("");
setConfirmPassword("");
};
return (
<div className="center">
<div className="auth">
<h1>Register Account</h1>
{error && <div className="auth__error">{error}</div>}
<form onSubmit={register} name="registration_form">
<input
type="name"
value={name}
placeholder="Enter your user name"
required
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
value={email}
placeholder="Enter your email"
required
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
value={password}
required
placeholder="Enter your password"
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="password"
value={confirmPassword}
required
placeholder="Confirm password"
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<button type="submit">Register</button>
</form>
<span>
Already have an account?
<Link to="/login">login</Link>
</span>
</div>
</div>
);
}
export default Register;
import "./profile.css";
import { useAuthValue } from "./AuthContext";
import { signOut } from "firebase/auth";
import { auth } from "./firebase";
function Profile() {
const { currentUser } = useAuthValue();
return (
<div className="center">
<div className="profile">
<h1>Profile</h1>
<p>
<strong>Name: </strong>
{currentUser?.name}
</p>
<p>
<strong>Email: </strong>
{currentUser?.email}
</p>
<p>
<strong>Email verified: </strong>
{`${currentUser?.emailVerified}`}
</p>
<span onClick={() => signOut(auth)}>Sign Out</span>
</div>
</div>
);
}
export default Profile;

Problem rendering data from Local Storage in React App

I have problem with rendering data from local storage on every refresh or reload. It renders only hard coded data but not data that I save in LS. It shows data in LS but not rendering. If anyone could explain or tell me what is wrong or give me directions to do something better would be grateful.I am farely new in Reactand would apretiate for insights. I ve put some dummy data. I ve sent componnets which could affect.
import { useState, useEffect } from "react";
//COMPONENTS:
import ScrollToTop from "./components/ScrollToTop";
import Footer from "./components/Footer";
import Home from "./components/Home";
import NavBar from "./components/NavBar";
import PhoneBook from "./components/PhoneBook";
function App() {
const date = new Date().toLocaleDateString();
const [contacts, setContacts] = useState([
{
id: Math.random().toString(36).substr(2, 9),
fullName: "Vekjko Petrovic",
address: "121 Town Commons Way Phoenix, AZ, 45215",
phone: 123_465_689,
date,
},
{
id: Math.random().toString(36).substr(2, 9),
fullName: "Marko Petrovic",
address: "Srbina 35, 11300 Smederevo Srbija",
phone: 256_269_866,
date,
},
{
id: Math.random().toString(36).substr(2, 9),
fullName: "Michael Jackson",
address: "52 City St, Detroit, Mi, 46218",
phone: 359_525_555,
date,
},
{
id: Math.random().toString(36).substr(2, 9),
fullName: "Vanessa Parady",
address: "11 Beogradska Beograd, SRB, 11000",
phone: 123_465_689,
date,
},
]);
useEffect(() => {
const savedContacts = JSON.parse(localStorage.getItem("contacts"));
if (savedContacts) {
setContacts(savedContacts);
}
}, []);
useEffect(() => {
localStorage.setItem("contacts", JSON.stringify(contacts));
}, [contacts]);
const [searchContact, setSearchContact] = useState("");
const [theme, setTheme] = useState("dark");
const changeTheme = () => {
theme === "dark" ? setTheme("light") : setTheme("dark");
};
const addContact = (fullName, phone, address, email) => {
const newContacts = {
id: Math.random().toString(36).substr(2, 9),
fullName,
address,
phone,
email,
date,
};
const newContact = [...contacts, newContacts];
setContacts(newContact);
};
const deleteContact = (id) => {
const remainedContacts = contacts.filter((item) => item.id !== id);
setContacts(remainedContacts);
};
return (
<div data-theme={theme} className="app-container">
<ScrollToTop />
<NavBar changeTheme={changeTheme} currentTheme={theme} />
<Home />
<PhoneBook
contacts={contacts.filter((contact) =>
contact.fullName.toLowerCase().includes(searchContact)
)}
handleAddContact={addContact}
deleteContact={deleteContact}
handleSearchContacts={setSearchContact}
/>
<Footer />
</div>
);
}
export default App;
import React from "react";
import "../index.css";
//ASSETS:
import NewContact from "./NewContact";
import Contact from "./Contact";
import Search from "./Search";
function PhoneBook({
contacts,
handleAddContact,
deleteContact,
handleSearchContacts,
}) {
return (
<div id="phone_book" className="contacts-list">
<Search handleSearchContacts={handleSearchContacts} />
{contacts.map((contact) => {
return (
<Contact
key={contact.id}
id={contact.id}
fullName={contact.fullName}
address={contact.address}
phone={contact.phone}
email={contact.email}
date={contact.date}
deleteContact={deleteContact}
/>
);
})}
<NewContact handleAddContact={handleAddContact} />
</div>
);
}
export default PhoneBook;
import React from "react";
import profile from "../assets/images/profile.png";
import { MdDeleteForever } from "react-icons/md";
function Contact({ fullName, address, phone, email, id, date, deleteContact }) {
return (
<div className="contact">
<p className="contact-header">
<span>
<i>{fullName} </i>
</span>
<img src={profile} alt="profile" />
</p>
<div className="contact-footer">
<p>
{" "}
<i>Address: </i>
{address}
</p>
<p>
<i>Phone:</i> {phone}
</p>
<p>
{" "}
<i>Email:</i> {email}
</p>
<MdDeleteForever
onClick={() => deleteContact(id)}
className="delete-icon"
size="1.3rem"
/>
<p className="span-date">
<i>Date: </i>
{date}
</p>
</div>
</div>
);
}
export default Contact;
import React, { useState } from "react";
function NewContact({ handleAddContact }) {
const [fullName, setFullName] = useState("");
const [phone, setPhone] = useState("");
const [address, setAddress] = useState("");
const [email, setEmail] = useState("");
const handleSaveClick = () => {
if (!(fullName.trim().length > 0)) {
return;
}
handleAddContact(fullName, phone, address, email);
setFullName("");
setPhone("");
setAddress("");
setEmail("");
};
return (
<div className="contact new last">
{" "}
<p className="inputs">
<span>Create New Contact</span>
<label>Full Name:</label>
<input
type="text"
placeholder="Enter..."
value={fullName}
onChange={(e) => setFullName(e.target.value)}
/>
<label> Address:</label>
<input
type="text"
placeholder="Enter..."
value={address}
onChange={(e) => setAddress(e.target.value)}
/>
<label> Phone:</label>
<input
type="text"
placeholder="Enter..."
value={phone}
onChange={(e) => setPhone(e.target.value)}
/>
<label>Email:</label>
<input
type="text"
placeholder="Enter..."
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</p>
{/* <img src={profile} alt="fullname" /> */}
<div className="save-list-footer">
<button className="save" onClick={handleSaveClick}>
SAVE
</button>
</div>
</div>
);
}
export default NewContact;
import styled from "styled-components";
import React from "react";
import { MdSearch } from "react-icons/md";
//STYLES
import "../index.css";
function Search({ handleSearchContacts }) {
return (
<SearchComponent className="search">
<MdSearch className="search-icon" size="1.3em" />
<input
type="text"
placeholder="Search..."
onChange={(e) => handleSearchContacts(e.target.value)}
/>
</SearchComponent>
);
}
export default Search;
Took me some messing around but I think I have an example that might be doing what you are describing. It seems like the following code may be the culprit:
useEffect(() => {
localStorage.setItem("contacts", JSON.stringify(contacts));
}, [contacts]);
Not in your example I assume you are initializing contacts like such:
const [contact, setContacts] = useState([])
When this state is initialized it will trigger that useEffect and set the localStorage.setItem("contacts" , []) which will make it look like nothing is being rendered. I think the easiest fix would be to move the localStorage.setItem into the addContacts function.
Here is a simplified version of how to set it up:
export const Contacts = () => {
const [contacts, setContacts] = useState([]);
useEffect(() => {
const savedContacts = localStorage.getItem("contacts");
if (savedContacts) {
setContacts(JSON.parse(savedContacts));
}
}, []);
// useEffect(() => {
// //This is your issue here Comment out this block and comment in the setItem in the addContact
// localStorage.setItem("contacts", JSON.stringify(contacts));
// }, [contacts]);
const addContact = (newContact) => {
const newContactList = [...contacts, newContact];
setContacts(newContactList);
localStorage.setItem("contacts", JSON.stringify(newContactList));
};
return (
<div>
<InputContact addContact={addContact} />
{contacts.map((data, i) => (
<Contact data={data} key={i} />
))}
</div>
);
};
You can find a working example of this on code sandbox. There is some explanation of the app in the App.js and Contacts.jsx. https://codesandbox.io/s/localstorage-contacts-s9dfzc?file=/src/Contacts.jsx:130-969

I want to pass [details] object from the current component to another component using navigate in react

While using the navigate and passing email in it, I am getting email in another component for first time only. Second time it is becoming undefined.
Please help me here to How can I send data using navigate from one component to another component. Here, after clicking on login button, it should redirect to desired page and should pass the details object.
Also I want to pass all the data available in details object to another component.
*This is studentStatus.js and this will recieve data from Login.js *
import { useLocation } from "react-router";
const Studentstatus = () => {
const {state} = useLocation();
console.log(state.email);
// const {id, firstname, lastname, email,password} = state;
return (
<>
{/* <p id="email" className="email">Email Id: -{state.email} </p><br/> */}
<div className="studentDetails">
<p id="id" className="id">ID: -{state.id}</p><br/>
<p id="fname" className="fname">First Name: - {state.firstname}</p><br/>
<p id="lname" className="lname">Last Name: -{state.lastname}</p><br/>
<p id="email" className="email">Email Id: -{state.email} </p><br/>
<p id="password" className="password">password Id: -{state.password} </p><br/>
</div>
</>
)
}
export default Studentstatus;
import './Login.css'
import { FcGoogle } from "react-icons/fc"
import { FaGithub, FaFacebook } from "react-icons/fa"
import { Link, Navigate } from 'react-router-dom'
import React,{ useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
const Login = () =>{
const showConsole =()=>{
//onclick it will display on console
console.log("I am google, facebook, github");
}
const navigate = useNavigate();
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [details, setDetails] = React.useState({});
function login(){
let item = {password, email};
console.log(item);
fetch("http://localhost:8080/student/login",{
method:'POST',
body:JSON.stringify(item),
headers:{
"Content-Type":'application/json',
"Accept":'application/json'
}
}).then((e)=>{
if(e.status === 200){
console.log("Success",e)
window.alert("Student Logged in successfully");
fetch(`http://localhost:8080/student/oneStudentEmail?email=${email}`,{
method:'GET',
headers:{
"Content-Type":'application/json',
"Accept":'application/json'
}
}).then((student)=>student.json())
.then((result)=>{
// console.log(result);
setDetails(result);
})
navigate("/student-status", {state:{email:details.email}})
}else{
console.log("Not found",e,item)
window.alert("Not found",item);
}
})
console.log(details);
}
return (
<>
<div className='main_login'>
<div><button className="btn_google" onClick={showConsole}><FcGoogle /></button></div>
<div><button className="btn_github" onClick={showConsole}><FaGithub /></button></div>
<div><button className="btn_facebook" onClick={showConsole}><FaFacebook /></button></div>
<div className="col-sm-6 offset-sm-3">
<h3>Enter Details</h3>
{/* input boxes */}
<input type="text" className="form-control" placeholder="Email" value={email} onChange={(e)=>{setEmail(e.target.value)}} /><br/>
<input type="password" className="form-control" placeholder="Password" value={password} onChange={(e)=>setPassword(e.target.value)} /><br/>
<button className="btn btn-primary" onClick={login} > Login </button><br/>
Already have an Account?<Link to="/sign-up">Sign Up</Link><br/>
</div>
{/* display details at the bottom but I want to pass data to another component */}
<div>
Id : -{details.id}<br/>
Name : -{details.firstname} {details.lastname}<br/>
Email: -{details.email}<br/>
Password: -{details.password}<br/>
</div>
</div>
</>
)
}
export default Login;

local storage is not persistent in react app

I am creating a react app which is using local storage. I am saving and array of objects to local storage.
when I try to save to local storage the data is saving.
and then when I refresh the page the saved data is becoming empty object,
like this [].
if any one knows why its happening please help me
import React, {useEffect, useState} from 'react';
import Addcontact from './Addcontact';
import './App.css';
import Contactlist from './Contactlist';
import { Header } from './Header';
function App() {
const keyy ="contactlist"
const [contacts, setcontacts] = useState([])
const contactshandler = (contact)=> {
console.log(contact)
setcontacts([...contacts, contact])
}
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])
useEffect(() => {
localStorage.setItem(keyy, JSON.stringify(contacts));
}, [contacts])
return (
<div className="ui container">
<Header />
<Addcontact contacts={contacts} contactshandler={contactshandler} />
<Contactlist contacts={contacts} />
</div>
);
}
app component
import React, { useState } from 'react'
function Addcontact({contacts, setcontacts, contactshandler}) {
const [user, setuser] = useState({username:'', email:''})
const addvalue = (e) => {
e.preventDefault();
console.log(user)
contactshandler(user)
setuser({username:'', email:''})
}
return (
<div>
<div className='ui main'>
<h2> Add Contact</h2>
<form className='ui form' onSubmit={addvalue}>
<div className=''>
<label>name</label>
<input name="name" placeholder='name' value={user.username} onChange={(e) => setuser({...user, username : e.target.value })} />
</div>
<div className='feild'>
<label>email</label>
<input email='email' placeholder='email' value={user.email} onChange={(e) => setuser({...user, email: e.target.value})} />
</div>
<button>add</button>
</form>
</div>
</div>
)
}
export default Addcontact
export default App;
add component
this is the value showing when saving after refresh this value becomes empty object
enter image description here
console
enter image description here
You don't need useEffect to read the data. You can initially read it.
const [contacts, setcontacts] = useState(JSON.parse(localStorage.getItem(keyy)) ?? [])
and remove
useEffect(() => {
const getdata = JSON.parse(localStorage.getItem(keyy))
getdata && setcontacts(getdata)
}, [])

Login page issues while using react js and Django api

I am creating a simple login page using react js and Django api. I am able to login but unable to go to my dashboard as it is throwing error like "Unhandled Rejection (TypeError): Cannot read property 'status' of undefined"
I am using Visual Studio Code
The full code is as below:
Login.js
import React, { useState } from 'react';
import axios from 'axios';
import { setUserSession } from './Utils/Common';
function Login(props) {
const [loading, setLoading] = useState(false);
const username = useFormInput('');
const password = useFormInput('');
const [error, setError] = useState(null);
// handle button click of login form
const handleLogin = () => {
setError(null);
setLoading(true);
axios.post('http://localhost:8000/account/user/signin', { mobile_number: username.value,
password: password.value }).then(response => {
setLoading(false);
setUserSession(response.data.token, response.data.user);
props.history.push('/dashboard');
}).catch(error => {
setLoading(false);
if (error.response.status === undefined) setError(error.response.data.message);
else setError("Something went wrong. Please try again later.");
});
}
return (
<div>
Login<br /><br />
<div>
Username<br />
<input type="text" {...username} autoComplete="new-password" />
</div>
<div style={{ marginTop: 10 }}>
Password<br />
<input type="password" {...password} autoComplete="new-password" />
</div>
{error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
<input type="button" value={loading ? 'Loading...' : 'Login'} onClick={handleLogin}
disabled={loading} /><br />
</div>
);
}
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
}
}
export default Login;
Dashboard.js
import React from 'react';
import { getUser, removeUserSession } from './Utils/Common';
function Dashboard(props) {
const user = getUser();
//handle click event of logout button
const handleLogout = () => {
removeUserSession();
props.history.push('/login');
}
return (
<div>
Welcome {user.name}!<br /><br />
<input type="button" onClick={handleLogout} value="Logout" />
</div>
);
}
export default Dashboard;

Categories

Resources