Pass Data between classes components (React) - html

I'm new to react and web dev in general. I need to pass a few values from a class to another when switching pages. My routes and links are working just fine.
I've tried a lot of stuff but I can't manage to pass the data to the class that is going to render the next page on the website. I need your help please ! (feel free to give me advice about the code, it's probably pretty shitty lol)
App.jsx
import React, { Component } from 'react'
import { BrowserRouter, Route, Routes} from 'react-router-dom';
import './App.css'
import SignIn from './SignIn/SignIn';
import Register from './Register/Register';
import Informations from './Register/Informations/Informations';
import PageNotFound from './PageNotFound/error';
import Photos from './Register/Informations/Photos/Photos'
class App extends Component {
render() {
return <BrowserRouter>
<Routes>
<Route path='/' element={<Register/>} exact/>
<Route path='/register' element={<Register/>}/>
<Route path='/sign-in' element={<SignIn/>}/>
<Route path='/infos' element={<Informations/>}/>
<Route path='/photos' element={<Photos/>}/>
<Route path='*' element={<PageNotFound/>}/>
</Routes>
</BrowserRouter>
}
}
export default App
Register.jsx (starting point of the site, I want the data to go from this class to the next one)
import React, { Component } from 'react';
import { Link } from "react-router-dom";
import './Register.scss'
import axios from 'axios'
import test_img from '../blink_logo.svg';
class Register extends Component
{
constructor (props) {
super(props);
this.state =
{
email: '',
firstname: '',
lastname: '',
telephone: '',
password: ''
}
this.handleLogin = this.handleLogin.bind(this);
}
handleLogin () {
axios.post('http://localhost:3000/api/user/', {email: this.state.email,
firstname: this.state.firstname,
lastname: this.state.lastname,
telephone: this.state.telephone,
password: this.state.password})
.then((response) =>
{
console.log(response);
this.setState({username: response.data.username})
}).catch(error =>
{
console.log(error);
})
console.log("Email: " + this.state.email);
console.log("Firstname: " + this.state.firstname);
console.log("Lastname: " + this.state.lastname);
console.log("Telephone: " + this.state.telephone);
console.log("Password: " + this.state.password);
}
handleEmailChange = (e) =>{
this.setState({email: e.target.value});
}
handleFirstnameChange = (e) =>{
this.setState({firstname: e.target.value});
}
handleLastnameChange = (e) =>{
this.setState({lastname: e.target.value});
}
handleTelephoneChange = (e) => {
this.setState({telephone: e.target.value});
}
handlePasswordChange = (e) => {
this.setState({password: e.target.value});
}
render () {
return (
<div>
<div className='image'>
< img src={test_img} alt="Blink Logo"/>
</div>
<div className='base-container-register'>
<div className='header'>Rejoindre l'aventure !</div>
<div className='content'>
<div className='form'>
<div className='label'>Email</div>
<div className='form-group'>
<input type="text" name="email" placeholder="email" value={this.state.email} onChange={this.handleEmailChange} />
</div>
<div className='label'>Prénom</div>
<div className='form-group'>
<input type="text" name="firstname" placeholder="prénom" value={this.state.firstname} onChange={this.handleFirstnameChange} />
</div>
<div className='label'>Nom</div>
<div className='form-group'>
<input type="text" name="lastname" placeholder="nom" value={this.state.lastname} onChange={this.handleLastnameChange} />
</div>
<div className='label'>Mot de passe</div>
<div className='form-group'>
<input type="password" name="password" placeholder="mot de passe" value={this.state.password} onChange={this.handlePasswordChange}/>
</div>
<div className='label'>Numéro de téléphone</div>
<div className='form-group'>
<input type="telephone" name="telephone" placeholder="numéro de téléphone" value={this.state.telephone} onChange={this.handleTelephoneChange}/>
</div>
</div>
<div className='footer' >
<Link to='/infos' state={{email: this.state.email}}>
<button onClick={this.handleLogin} className='footer'>Se lancer</button>
</Link>
{/* <Link to='/infos' params={email: this.state.email}>
<button onClick={this.handleLogin} className='footer'>Se lancer</button>
</Link> */}
</div>
</div>
</div>
<div className='redirect-to-signin'> Vous avez déjà un compte ? <Link to='/sign-in'>Sign in</Link> </div>
</div>
);
}
}
export default Register
Informations.jsx (where I want to grab the data from Register)
class Informations extends Component
{
constructor (props) {
super(props);
this.state =
{
username: '',
workInfo: '',
webSite: '',
socialId: '',
file: null,
file_name: '...'
}
this.handleLogin = this.handleLogin.bind(this);
this.handlePhotoChange = this.handlePhotoChange.bind(this)
}
I'm using react-router-dom v6.
Thank you in advance for your help.

When calling your Informations class just pass the values you want to send, as parameters.
<Informations value1={4} value2={8} />
To get the data you are sending from inside the Informations class:
this.props.value1

With v6 of react-router-dom, we can pass props to our components using the following method:
<Route path='/infos' element={<Informations value1={4} value2={8} />}/>
However, you are suggesting that values from the Register component need to make their way over to the Informations component. The better method for passing those values around would be to take advantage of React Context.
Using Context, you could have some state defined in a custom context that you can set in Register, and read in Informations.

Related

how to use onSubmit in react-router while onSubmit checks the details in the form and if it's correct he pass with Link="" to another component

I'm trying to use onSubmit in the form, I wand it to check the details in the form and according to the details to decide if I want to pass to another component with Link in react-router how can I do that, how to write the Link (and it will pass only when I want in the onSubmit function)?
this is my routing-code:
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import LogIn from "./components/LogIn";
import HomePage from "./HomePage";
import Todos from "./components/Todos";
import Albums from "./components/Albums";
import Info from "./components/Info";
import Posts from "./components/Posts";
function App() {
return (
<Router>
<div>
<Routes>
<Route path="/" pelement={<HomePage />} />
<Route path="/login" element={<LogIn />} />
<Route path="/todos" element={<Todos />} />
<Route path="/info" element={<Info />} />
<Route path="/albums" element={<Albums />} />
<Route path="/posts" element={<Posts />} />
</Routes>
</div>
</Router>
);
}
export default App;
and I want that when I will click on the submit here(down- in the log in component) it will control on the Link="/" that will happen only if onSubmit decide
import { FormEventHandler } from "react";
function LogIn() {
const [inputField, setInputField] = useState({
user_name: "",
password: "",
});
const inputChange = (e) => {
e.preventDefault();
setInputField((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
};
const submitButton = (e) => {
e.preventDefault();
if(**the details in the form are correct**)
**add the details to local storage and pass to home page with:<Link to="/"></Link>**
else
alert("details are not correct");
};
return (
<form onSubmit={submitButton}>
<label>Enter you user name</label>
<input
type="text"
name="user_name"
onChange={inputChange}
placeholder="Your user name"
value={inputField.user_name}
/>
<br />
<label>Enter you password</label>
<input
type="password"
name="password"
onChange={inputChange}
placeholder="Your password"
value={inputField.password}
/>
<br />
<button type="submit" >Log In</button>
</form>
);
}
export default LogIn;
You can't return a Link component in a callback like this and expect it to be rendered and do anything in the DOM. In callbacks you will need to issue an imperative navigation action using the navigate function.
Example:
import { useNavigate } from 'react-router-dom';
function LogIn() {
const navigate = useNavigate();
...
const submitButton = (e) => {
e.preventDefault();
if (**the details in the form are correct**) {
// add the details to local storage
localStorage.setItem("details", details);
// and pass to home page
navigate("/", { state: { details } });
} else {
alert("details are not correct");
}
};
...

V6 React Router Dom Routes are not working

I am trying to build a React register and login with JWT tokens and I am hitting a wall.
When I click on the register button it should take me to the login. And from there I should be able to login and see the dashboard.
When I click on register, nothing happens. I replaced useHistory with useNavigate and .history.push with navigate but still nothing.
I'm using MAMP for my db.
App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Dashboard from "./components/Dashboard";
import Login from "./components/Login";
import Navbar from "./components/Navbar";
import Register from "./components/Register";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/dashboard" element={<><Navbar /><Dashboard /></>} />
</Routes>
</BrowserRouter>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import "bulma/css/bulma.css";
import axios from "axios";
axios.defaults.withCredentials = true;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Dashboard.js
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import jwt_decode from "jwt-decode";
import { useNavigate } from 'react-router-dom';
const Dashboard = () => {
const [name, setName] = useState('');
const [token, setToken] = useState('');
const [expire, setExpire] = useState('');
const [users, setUsers] = useState([]);
const navigate = useNavigate();
useEffect(() => {
refreshToken();
getUsers();
}, []);
const refreshToken = async () => {
try {
const response = await axios.get('http://localhost:3306/token');
setToken(response.data.accessToken);
const decoded = jwt_decode(response.data.accessToken);
setName(decoded.name);
setExpire(decoded.exp);
} catch (error) {
if (error.response) {
navigate("/");
}
}
}
const axiosJWT = axios.create();
axiosJWT.interceptors.request.use(async (config) => {
const currentDate = new Date();
if (expire * 1000 < currentDate.getTime()) {
const response = await axios.get('http://localhost:3306/token');
config.headers.Authorization = `Bearer ${response.data.accessToken}`;
setToken(response.data.accessToken);
const decoded = jwt_decode(response.data.accessToken);
setName(decoded.name);
setExpire(decoded.exp);
}
return config;
}, (error) => {
return Promise.reject(error);
});
const getUsers = async () => {
const response = await axiosJWT.get('http://localhost:3306/users', {
headers: {
Authorization: `Bearer ${token}`
}
});
setUsers(response.data);
}
return (
<div className="container mt-5">
<h1>Welcome Back: {name}</h1>
<table className="table is-striped is-fullwidth">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{users.map((user, index) => (
<tr key={user.id}>
<td>{index + 1}</td>
<td>{user.name}</td>
<td>{user.email}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
export default Dashboard
Login.js
import React, { useState } from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();
const Auth = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:3306/login', {
email: email,
password: password
});
navigate("/dashboard");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}
return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Auth} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Email or Username</label>
<div className="controls">
<input type="text" className="input" placeholder="Username" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Login</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}
export default Login
Navbar.js
import React from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Navbar = () => {
const navigate = useNavigate();
const Logout = async () => {
try {
await axios.delete('http://localhost:3306/logout');
navigate("/");
} catch (error) {
console.log(error);
}
}
return (
<nav className="navbar is-light" role="navigation" aria-label="main navigation">
<div className="container">
<div className="navbar-brand">
<a className="navbar-item" href="https://bulma.io">
<img src="https://bulma.io/images/bulma-logo.png" width="112" height="28" alt="logo" />
</a>
<a href="/" role="button" className="navbar-burger burger" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" className="navbar-menu">
<div className="navbar-start">
<a href="/" className="navbar-item">
Home
</a>
</div>
<div className="navbar-end">
<div className="navbar-item">
<div className="buttons">
<button onClick={Logout} className="button is-light">
Log Out
</button>
</div>
</div>
</div>
</div>
</div>
</nav>
)
}
export default Navbar
Register.js
import React, { useState } from 'react'
import axios from "axios";
import { useNavigate } from "react-router-dom";
const Register = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confPassword, setConfPassword] = useState('');
const [msg, setMsg] = useState('');
const navigate = useNavigate();
const Register = async (e) => {
e.preventDefault();
try {
await axios.post('http://localhost:3306/users', {
name: name,
email: email,
password: password,
confPassword: confPassword
});
navigate("/");
} catch (error) {
if (error.response) {
setMsg(error.response.data.msg);
}
}
}
return (
<section className="hero has-background-grey-light is-fullheight is-fullwidth">
<div className="hero-body">
<div className="container">
<div className="columns is-centered">
<div className="column is-4-desktop">
<form onSubmit={Register} className="box">
<p className="has-text-centered">{msg}</p>
<div className="field mt-5">
<label className="label">Name</label>
<div className="controls">
<input type="text" className="input" placeholder="Name"
value={name} onChange={(e) => setName(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Email</label>
<div className="controls">
<input type="text" className="input" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<label className="label">Confirm Password</label>
<div className="controls">
<input type="password" className="input" placeholder="Confirm Password" value={confPassword} onChange={(e) => setConfPassword(e.target.value)} />
</div>
</div>
<div className="field mt-5">
<button className="button is-success is-fullwidth">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
)
}
export default Register
I don't think need the '/' in the routes, and you can just navigate to "register" and "dashboard". Only use anchor tags when linking to external pages. For internal navigation use Link tags: <Link to="about">About</Link> or navigate() for buttons.
The snippet below is modified from my code. Before the user is signed in (not authorized), show your marketing pages and the sign-in / sign-up buttons. Show marketing page by default, and sign-in / sign-up buttons will navigate to "enter" or similar. The * catch-all route will catch this and show your sign-in/sign-up page. Also, if someone is coming from a bookmark the "*" route catches that and directs them to sign-up, which perhaps they bounce through and get to the intended destination.
Once user is authenticated, return the 'dashboard' routes.
Note how the dashboard routes are nested and there's a component that wraps them all (good for your navbar). You put <Outlet/> into that component and any nexted routes will render where the outlet is. Also, within those routes, navigation is relative. ie. you can navigate(jobId) and not navigate(`jobs/${jobId}`).
const unauthenticatedRoutes = (
<Routes>
<Route path="/" element={<MarketingWrapper />}>
<Route index element={<MarketingHome />
<Route path="*" element={<SignUpSignIn />} />
</Route>
</Routes>
)
const authenticatedRoutes = (
<Routes>
<Route path="/" element={<DashboardWrapper />}>
<Route index element={<Dashboard />
<Route path="*" element={<NoMatch />} />
<Route path="enter" element={<SignUpSignIn />} />
<Route path='signout' element={<SignOut signOut={signOut} />} />
<Route path="jobs" element={<JobsList jobId={jobId!} />}>
<Route path=":jobId" element={<JobPage />} />
<Route index element={<JobNew jobId={jobId!} />} />
</Route>
</Route>
</Routes>
)
return (
isAuthenticated ? authenticatedRoutes : unauthenticatedRoutes
)

show login page for a second when routering other pages reactJS

I use this video https://www.youtube.com/watch?v=r4EsP6rovwk&t=1s to create an Auth for my website,
i basically copied his code the only change is that I route after successful login to different page.
the problem is that after login my home page is shown, but when I'm pressing buttons to route for other pages, before the other page is shown I see for a second the login page.
this is the code of the auth - I believe it connect to the problem (before this my website has worked well).
Edit:
i try to figure out what's the problem and I've noticed that when i'm using link everything's fine, but when using href there's a problem.
(And that's what I did in my website).
So... does anyone know why href makes this issue?
app.js
import React, { Component } from 'react';
import fire from './Fire';
import SearchAppBar from '../components/appBar';
import Login from './login';
class App extends Component {
constructor() {
super();
this.state = ({
user: null,
});
this.authListener = this.authListener.bind(this);
}
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ user });
} else {
this.setState({ user: null });
}
});
}
render() {
return (
<div>{this.state.user ? ( <SearchAppBar/>) : (<Login />)}</div>)
}
}
export default App;
login.js:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import fire from './Fire';
class Login extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.handleChange = this.handleChange.bind(this);
this.signup = this.signup.bind(this);
this.state = {
email: '',
password: ''
};
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
login(e) {
e.preventDefault();
fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((u)=>{
}).catch((error) => {
console.log(error);
});
}
signup(e){
e.preventDefault();
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((u)=>{
}).then((u)=>{console.log(u)})
.catch((error) => {
console.log(error);
})
}
render() {
return (
<div className="col-md-6">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input value={this.state.email} onChange={this.handleChange} type="email" name="email"
class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter
email" />
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input value={this.state.password} onChange={this.handleChange} type="password" name="password"
class="form-control" id="exampleInputPassword1" placeholder="Password" />
</div>
<button type="submit" onClick={this.login} className="btn btn-primary">Login</button>
<button onClick={this.signup} style={{marginLeft: '25px'}} className="btn btn-
success">Signup</button>
</form>
</div>
);
}
}
export default Login;
Thank you all guys!!

How to login validation using my api in React Js

React JS
I'm new to react js
In my api there is username and password. If the user login, have to validate from my json value
handleSubmit(e) {
fetch('https://randomuser.me/api?results=1')
.then((response) => {
return response.json()
.then((json) => {
if (response.ok) {
return Promise.resolve(json)
}
return Promise.reject(json)
})
})
alert(json) not working to check the result.
How can i fetch the username and password in the response?
And how to take this next page if the user was logged in successfully ?
My full Code
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
const ReactCSSTG = CSSTransitionGroup;
class App extends Component {
constructor(props) {
super(props);
this.state = {
isVisible: true
}
// Bindings
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemount = this.handleRemount.bind(this);
}
handleSubmit(e) {
alert("dsa");
fetch('https://randomuser.me/api?results=1')
.then((response) => {
return response.json()
.then((json) => {
if (response.ok) {
return Promise.resolve(json)
}
return Promise.reject(json)
})
})
}
handleRemount(e) {
this.setState({
isVisible: true
}, function () {
console.log(this.state.isVisible)
});
e.preventDefault();
}
render() {
// const for React CSS transition declaration
let component = this.state.isVisible ? <Modal onSubmit={this.handleSubmit} key='modal' /> : <ModalBack onClick={this.handleRemount} key='bringitback' />;
return <ReactCSSTG transitionName="animation" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{component}
</ReactCSSTG>
}
}
// Modal
class Modal extends React.Component {
render() {
return <div className='Modal'>
<Logo />
<form onSubmit={this.props.onSubmit}>
<Input type='text' name='username' placeholder='username' />
<Input type='password' name='password' placeholder='password' />
<button> Sign In</button>
</form>
<a href='#'>Lost your password ?</a>
</div>
}
}
// Generic input field
class Input extends React.Component {
render() {
return <div className='Input'>
<input type={this.props.type} name={this.props.name} placeholder={this.props.placeholder} required />
<label htmlFor={this.props.name}></label>
</div>
}
}
// Fake logo
class Logo extends React.Component {
render() {
return <div className="logo">
<i><img src={logo} className="App-logo" alt="logo" /></i>
<span> Test </span>
</div>
}
}
// Button to brind the modal back
class ModalBack extends React.Component {
render() {
return (
<button className="bringitback" onClick={this.props.onClick} key={this.props.className}>Back to login page!</button>
);
}
}
export default App;
Thanks in Advance!
If you just want to catch data for now this will do the trick
fetch('https://randomuser.me/api?results=1')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
fetch('https://randomuser.me/api?results=1')
.then((response) => {
// check for status code from service if success
// set response in state such as login success
this.route.navigate(['/']);
})
.catch(error =>{
console.log(error);
});
})
Taking user to next page. Use react router for achieving this.
Step 1: Wrap your <App /> inside <BrowserRouter />
Now validate response if username/password are correct using service call.
Then this.route.navigate(['/']);
This will navigate user to home page of app after successful login.
Heres What I did, keep in mind I set up my backend with express/node.
I used Axios to fetch from my api.
onSubmit = (e) => {
e.preventDefault();
axios.get('API_PATH')
.then(res => {
const user = res.data[0].username;
const password = res.data[0].password;
const username = this.state.username;
const passwordEntered = this.state.password;
if(username === '' && passwordEntered === ''){
document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
}else if(user === username && passwordEntered === password){
document.getElementById('status').innerHTML = '';
console.log(user, password)
}else{
document.getElementById('status').innerHTML = '<p>Please Enter A Valid Username and Password</p>';
}
})
.catch(error => {
console.log(error);
});
}
Here is the form I used.
<Form
>
<Form.Row>
<Form.Group as={Col}>
<Form.Label>Username</Form.Label>
<Form.Control
type="text"
name="username"
id="username"
value={this.state.value}
onChange={this.handleChange}
>
</Form.Control>
</Form.Group>
<Form.Group as={Col}>
<Form.Label>Password</Form.Label>
<Form.Control
type="text"
id="password"
name="password"
value={this.state.value}
onChange={this.handleChange}
/>
</Form.Group>
</Form.Row>
<Button className="btn btn-sm btn-light" onClick={this.onSubmit}>
<i style={redColor} className="fas fa-sign-in-alt"></i> Login
</Button>
</Form>

React JS authentication

Im new to react js. I am having trouble understanding how to use store. Can anyone help me with the very basic way to create login and handle redirects?
Im creating a simple 2 page application. I want the user to redirect to login page if he is not authorized. Also if anyone has a link to good tutorials for react js kindly share.
index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import './index.css';
strong text
import Create from "./components/createshipment";
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';
import {Switch, Redirect} from 'react-router-dom';
import Route from 'react-router-dom/Route';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Router>
<div className="App">
<Switch>
<Route path="/login" exact strict component={App} />
<Route path="/cs" component={Create} />
</Switch >
</div>
</Router>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import Login from "./components/login";
import "./components/App.css";
class App extends Component {
constructor(props){
super(props);
// this.onHandle = this.onHandle.bind(this);
}
state={
logged:false,
}
onHandle =(e)=>{
return this.setState({ logged: e});
}
render() {
return (
<div >
<Login logged={this.state.logged} onHandle={e=>this.onHandle(e)} />
</div>
);
}
}
export default App;
Login.js
import React, { Component } from 'react';
import './App.css';
// import er from "./error.png";
import Create from "./createshipment";
import { Route, Link, Switch, Redirect } from 'react-router-dom';
class Login extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
state={
username:"",
password:"",
flag: false,
showResults:false,
}
isLoggedIn(){
// console.log(Login.flag);
return this.state.flag;
}
onChange =(e)=>{
return this.setState({
[e.target.name]: e.target.value,
});
}
onSubmit = async (event) =>{
// debugger;
event.preventDefault();
const { username, password,flag} = this.state;
this.setState({ flag: false });
if (!(username === 'george' && password === 'george')) {
this.username="";
this.password="";
alert('Invalid username/password');
return false;
}
else{
console.log("abc")
this.props.onHandle(true);
return true;
}
}
render() {
if (this.props.logged === true) {
return <Redirect to='/cs'/>
}
// <div className="errormain">
// { this.state.showResults ? <label className="ErrorMsg"> Invalid Login Details</label> : null }
// </div>
return (
<div className="App">
<form className="frame" >
<h1 className="App-title">ALPHA</h1>
<h2 className="App-para"> Aid Tracking Portal</h2>
<br/><br/> <br/>
<br/><br/><br/>
<br/><br/><br/> <br/>
<br/><br/>
<input required="required" placeholder= "Username" className="lmain" name="username" placeholders='Email' onChange={e=> this.onChange(e)} value={this.state.username}/>
<br/>
<input type="text" required placeholder= "Password" className="lmain" name="password" placeholders='Password' type='password' onChange={e=> this.onChange(e)} value={this.state.password}/>
<button className="LB" value="true" onClick={this.onSubmit} > Login</button>
</form>
</div>
);
}
}
export default Login
CreateShipment.js
import React, { Component } from 'react';
// import logo from '/home/zubair/Desktop/projectmanager/src/logo.svg';
import NewShipment from './form/NewShipment.js';
import Navigation from './navigation';
import './form/createshipment.css';
class Createshipment extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div >
<header className="App-header">
<h1 className="App-title2">Aid Tracker</h1>
<Navigation/>
</header>
<br/><br/>
<NewShipment />
</div>
);
}
}
export default Createshipment;
On web you can use LocalStorage to store data.If you plan to use Redux then I would suggest github.com/rt2zz/redux-persist.