how to connect a handleSubmit to another page with condition in react? - javascript

when the user fills the sing up form and clicks the sing up button it has to be two scenarios
first: if the password and confirm password is matching it has to route to the dashboard page
second: if the password and confirm password is not matching it has to alert a massage ("Passwords do not match")
mine I used condition at Log.jsx down below for a function called handlesubmit , in that condition the first part of the condition is not working but the second part of the condition that regarding the second scenario is working and alerting the massage
here is my code and some screenshots
Log.jsx
import React from "react";
import "./log.css";
import { useState } from "react";
import { Link } from "react-router-dom";
export default function Log() {
const [formData, setFormData] = useState({
fullName: "",
email: "",
password: "",
passwordConfirm: "",
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
}
function handleSubmit(event) {
event.preventDefault();
if (formData.password === formData.passwordConfirm) {
return (
<Link className="link" to={"/Dashboard"}>
</Link>
);
} else {
alert("Passwords do not match");
return;
}
}
return (
<div className="loginn">
<div className="login-items">
<div className="title-log">
<p className="login-title">sing up</p>
</div>
<form className="form" onSubmit={handleSubmit}>
<span className="fullname">Fullname</span>
<input
className="input-lg"
type="name"
placeholder="Email address"
name="fullName"
onChange={handleChange}
value={formData.fullName}
></input>
<span className="email">Email</span>
<input
className="input-lg"
type="email"
name="email"
onChange={handleChange}
value={formData.email}
></input>
<span className="password">Password</span>
<input
className="input-lg"
type="password"
name="password"
onChange={handleChange}
value={formData.password}
></input>
<span className="password">Confirm Password</span>
<input
className="input-lg"
type="password"
name="passwordConfirm"
onChange={handleChange}
value={formData.passwordConfirm}
></input>
<button className="login-btn">Sing up</button>
</form>
</div>
</div>
);
}
Home.jsx
import React from 'react'
import Naav from '../../components/naav/Naav'
import Log from '../../components/log/Log'
import Footer from '../../components/footer/Footer'
export default function Home() {
return (
<div className='home'>
<Naav/>
<Log/>
<Footer/>
</div>
)
}
Dashboard.jsx
import React from "react";
import "./dashboard.css"
import Sidebar from "../../components/sidebar/Sidebar";
import Navtwo from "../../components/navtwo/Navtwo";
import Cards from "../../components/cards/Cards";
import Data from "../../components/data/Data";
import Title from "../../components/title/Title";
export default function Dashboard() {
return( <div className="dashboard">
<Sidebar/>
<Navtwo/>
<Title/>
<Cards/>
<Data/>
</div>
)
}
app.js
import React from "react";
import "./app.css";
import Headerr from "./components/headerr/Headerr";
import Naav from "./components/naav/Naav";
import Footer from "./components/footer/Footer";
import Log from "./components/log/Log";
import Sidebar from "./components/sidebar/Sidebar";
import Navtwo from "./components/navtwo/Navtwo";
import Cards from "./components/cards/Cards";
import Title from "./components/title/Title";
import Data from "./components/data/Data";
import Dashboard from "./pages/dashboard/Dashboard";
import Home from "./pages/home/Home";
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
export default function App() {
const currentUser = false;
return (
<Router>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/Dashboard" element={<Dashboard />} />
</Routes>
</Router> );
}

In your handleSubmit function, you return the Link component.
That does nothing!
There are 2 ways you can go about here.
Create a state passwordMatch, and set it inside handleSubmit. If the passwords do not match, return the Redirect element instead of the form.
Import the history and call it to navigate where you want inside the handleSubmit

Related

Reactjs - Cant render functional component

I'm trying to render a functional component. But for some reason, I'm getting this sentence on the console You need to enable JavaScript to run this app.
This is App.js
import './App.css';
import Home from './components/pages/home/Home';
import SignUp from './components/pages/sign/SignUp';
import Checking from './components/pages/sign/Checking';
import Login from './components/pages/sign/Login';
import Summery from './components/pages/summery/Summery';
import UserList from './components/pages/users/Users';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import UploadFiles from './components/pages/files/UploadFiles';
function App() {
return (
<Router>
<Routes>
<Route exact path='/' element= {<Home />}/>
<Route path='/sign-up' component= {Checking } />
<Route path='/log-in' element= {<Login />} />
<Route path='/admin' element= {<Summery />} />
<Route path='/users' element= {<UserList />} />
<Route path='/files' element= {<UploadFiles />} />
</Routes>
</Router>
);
}
export default App;
Home, Login, Summery, UserList and UploadFiles are React Components and not functions.
Only Checking is a function (Trying to convert everything to a function component).
They all render but only Checking logging into console You need to enable JavaScript to run this app.
This is Checking.js file
import React from "react";
import '../../../App.css';
import Button from '#material-ui/core/Button';
import SendIcon from '#material-ui/icons/Send';
import axios from 'axios';
import bcrypt from 'bcryptjs';
import Navbar from "../../navbar/Navbar";
import { useNavigate } from 'react-router-dom';
export default function Checking() {
const [companyID, setCompanyID] = React.useState('');
const [email, setEmail] = React.useState('');
const navigate = useNavigate();
function handleSubmit(Event) {
Event.preventDefault();
axios.post('/sign-up', {
companyID: companyID,
email: email})
.then(res =>{
//console.log(res.json());
console.log(res);
if(res.status === 200){
//this.app();
//history.push('/login');
}else if (res.status === 400){
console.log("duplicate ID");
}
}).catch(err =>{
// console.log("duplicate ID");
// console.log(err);
});
}
}
return (
<>
<Navbar />
<div className="register-container" ref={this.props.containerRef}>
<h1 className="sign-up">SIGN UP</h1>
<form onSubmit={handleSubmit}>
<div className="form">
<div className="form-group">
{/* <label htmlFor="company id">Company ID : </label> */}
<input
type="number"
name="companyID"
placeholder="Company id"
value={companyID}
onChange={(e) => setCompanyID(e.target.value)}
required/>
</div>
{ <div className="form-group">
{/* <label htmlFor="email">Email : </label> */}
<input
type="text"
name="email" placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required/>
</div> }
<div className="registerbtn">
{/* <button type="submit" class="btn btn-primary">Submit</button> */}
<Button type="submit" endIcon={<SendIcon />} color="primary" variant="contained">
Sign Up
</Button>
</div>
</div>
</form>
</div>
</>
);
}
What am I doing wrong?
Checking is also a react component and you need to render it like the others.
<Route path='/sign-up' element= {<Checking/> } />

how to connect two component when i click on submit button

I have some user components on which I used the navigation component and I am routing two components on it. when I click on the Device.js component button it should remove device.js and it should redirect to the Keyregister.js component which is having navigation component in it .It should change the value according to the props sent to it. But it is not happening.
user.js
import React from "react";
import { Route, Switch } from "react-router";
import "./User.css";
import Navigation from "./Dashboard/Navigation";
import AuthModel from "./Dashboard/AuthModel";
import DeviceDetails from "./Dashboard/DeviceDetails";
function User() {
return (
<>
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"}
/>
<Switch>
<Route path="/User/Dashboard/AuthModel" component={AuthModel} />
<Route path="/User/Dashboard/DeviceDetails" component={DeviceDetails} />
</Switch>
</>
);
}
export default User;
Navigation.js
import React from "react";
import "./Navigation.css";
import { Link } from "react-router-dom";
import { useHistory } from "react-router";
import { Image } from "react-bootstrap";
import EvoVert from "../../../Resources/EvoluteVert.png";
function Navigation(props) {
const history = useHistory();
const handleLogout = (e) => {
e.preventDefault();
localStorage.removeItem("accessToken");
localStorage.removeItem("roleType");
history.push("/");
};
return (
<>
<main classMain="main">
<aside className="sidebar ">
<Image className="Evo-logo" src={EvoVert} />
<nav className="nav">
<ul style={{ textDecoration: "none" }}>
<li>
<Link to={`/User/Dashboard/${props.link2}`}>
{props.link2name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link1}`}>
{props.link1name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link3}`}>
{props.link3name}
</Link>
</li>
</ul>
</nav>
</aside>
</main>
</>
);
}
export default Navigation;
Device.js
import React, { useState, useEffect } from "react";
import { Form } from "react-bootstrap";
import "./Dashboard.css";
import { useHistory } from "react-router";
import KeyRegister from "./KeyRegister";
function DeviceDetails() {
const history = useHistory();
const [visible, setvisible] = useState(true);
const [serialNum, setSerialNum] = useState("");
const [slot, setSlot] = useState("");
const frmsubmit = (e) => {};
return (
<>
<section className="device-Details_Dashboard">
<div className="container">
<div
className="heading"
style={{
color: "#312450",
fontWeight: "400",
fontSize: "35px",
padding: "1rem",
}}
>
DEVICE DETAILS
</div>
<Form onSubmit={frmsubmit}>
<div>
<div className="device-details-box">
<label>Serial Number</label>
<br />
<input
type="text"
value={serialNum}
onChange={(e) => setSerialNum(e.target.value)}
/>
</div>
<div className="device-details-box">
<label>Slot Number</label>
<br />
<input
type="text"
value={slot}
onChange={(e) => setSlot(e.target.value)}
/>
</div>
</div>
<button className="devDetSub" onClick={frmsubmit}>
<span>SUBMIT</span>
</button>
</Form>
</div>
</section>
{visible && <KeyRegister />}
</>
);
}
export default DeviceDetails;
KeyRegister.js
import React, { useState, useEffect } from "react";
import "./Navigation.css";
import { Route, Switch } from "react-router";
import DUPKT from "./DUPKT";
import MasterSession from "./MasterSession";
import AES from "./AES";
import Navigation from "./Navigation";
function KeyRegister() {
return (
<>
<Navigation
link1={"DUPKT"}
link2={"MasterSession"}
link3={"AES"}
link1name={"DUPKT"}
link2name={"MASTER KEY"}
link3name={"AES"}
/>
<main classMain="main">
<Switch>
<Route path="/User/Dashboard/DUPKT" component={DUPKT} exact />
<Route
path="/User/Dashboard/MasterSession"
component={MasterSession}
exact
/>
<Route path="/User/Dashboard/AES" component={AES} exact />
</Switch>
</main>
</>
);
}
export default KeyRegister;
I cannot see anywhere in your naviagation component props you are passing device details.
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"} //should have device details in props
/>

Failed prop type: The prop `setToken` is marked as required in `Login`, but its value is `undefined`

So, I'm new at React and I was making a WebApp using the API made by me that is full functional. I wanted to use token in sign in as the API is also prepared. Went to check a tutorial but it wont work because of the setToken.
I have no idea if is because of the fetch or anything else.
This is the error that appears when loading the page:
enter image description here
Then when I click the sign in button will always appear me this:
enter image description here
import React, { useContext, useState } from 'react';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import './App.css';
import ListGlucoseRecords from './screens/glucoseRecords/listGlucoseRecords';
import ListInsulineRecords from './screens/insulineRecords/listInsulineRecords';
import DashboardComp from './screens/dashboard/dashboardComp';
import ClientList from './screens/users/clientList';
import Login from './screens/login/Login';
import SignUp from './screens/signUp/SignUp';
function App() {
const [token, setToken] = useState([]);
if(!token) {
return <Login setToken={setToken} />
}
return (
<Router>
<Routes>
<Route path='/dashboard' element={<DashboardComp/>}/>
<Route path='/users' element={<ClientList/>}/>
<Route path='/glucose' element={<ListGlucoseRecords/>}/>
<Route path='/insuline' element={<ListInsulineRecords/>}/>
<Route path='/' element={<Login/>}/>
<Route path='/signUp' element={<SignUp/>}/>
</Routes>
</Router>
);
}
export default App;
import React, { useState } from 'react';
import './Login.css';
import logo from '../../images/HealthControl.png';
import { Link } from 'react-router-dom';
import { URL } from '../../components/apiURL';
import axios from 'axios';
import PropTypes from 'prop-types';
async function loginUser(credentials) {
return fetch(`${URL}/user/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(data => data.json())
}
export default function Login({ setToken }) {
const [email, setEmail] = useState([]);
const [password, setPassword] = useState([]);
const handleSubmit = async e => {
e.preventDefault();
const token = await loginUser({
email,
password
});
setToken(token);
}
return (
<body>
<div class="Login">
<div class="columns is-vcentered">
<div class="login column is-4 ">
<section class="section">
<div class="has-text-centered">
<img class="login-logo has-background-primary" src={logo} alt="Logo" />
</div>
<form onSubmit={handleSubmit}>
<div class="field">
<label class="label">Username</label>
<div class="control has-icons-right">
<input class="input" type="text" onChange={e => setEmail(e.target.value)}></input>
<span class="icon is-small is-right">
<i class="fa fa-user"></i>
</span>
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control has-icons-right">
<input class="input" type="password" onChange={e => setPassword(e.target.value)}></input>
<span class="icon is-small is-right">
<i class="fa fa-key"></i>
</span>
</div>
</div>
<div class="has-text-centered">
<button type="submit" class="button is-vcentered is-primary is-outlined">Login</button>
</div>
</form>
<div class="has-text-centered">
<Link to='/signUp' className="nav-links">
<a> Don't you have an account? Sign up now!</a>
</Link>
</div>
</section>
</div>
<div id="particles-js" class="interactive-bg column is-8">
</div>
</div>
</div>
</body>
);
};
Login.propTypes = {
setToken: PropTypes.func.isRequired
};
It's not clear what you want to do exactly but I think there are a couple of issues in your code:
You're using useContext and passing in an empty array. This hook expects a context object created via React.createContext.
Also, the idea with context is that you wrap your components in a context provider so any children can access that context. This way they can access state without having to pass down properties.
But you're not using a context provider, you're passing down setToken anyway.
Login requires setToken, but on this line
<Route path='/' element={}/>
you're not passing it down. So you get errors because setToken is undefined inside Login and it is a required property.
What I think you want to do is:
Use useState instead of useContext. Don't define the initial value of token, so the if (!token) is true initially, and false after you call setToken.
const App = () => {
const [token, setToken] = useState();
if (!token) {
return <Login setToken={setToken} />;
}
return (
<Router>
<Routes>
<Route path="/login" element={<Login setToken={setToken} />} />{" "}
</Routes>
</Router>
);
};
Even this would be a bit weird because after logging in you'd show the login page again, as this is the default route. Probably not what you want to do.
I suggest you think well about the solution before you start coding.
This is caused because you have used useContext to create a state, you should instead use useState.
useState takes in initial state value returns stateful value and a function to update it.
useContext takes in Context returns value that is returned by Context.Provider
more about useContext
const [token, setToken] = useState(/* initial state value */);

reactjs preventDefault() is not preventing the page reload on form submit

EDIT: Events are not working at all, the onSubmit and onChange functions are not being called. I have another reactapp with similar form and onChange and onSubmit works OK there.
I have a form I dont want the page to refresh when I click on submit. I tried using preventDefault() but I didnt work. Even onChange is printing anything on console. This form is not on page, I am using React Router to point to='/new' and component={NewPost} (NewPost is in ./components/posts/form)
./components/posts/form.js:
import React, { Component } from "react";
import { connect } from "react-redux";
class NewPost extends Component {
state = {
title: "",
body: "",
status: 0,
};
onSubmit = (e) => {
e.preventDefault();
const post = e;
console.log(post);
};
onChange = (e) => {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
const { title, body, status } = this.state;
return (
<div className="card card-body mt-4 mb-4">
<h2>New Post</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Title</label>
<input
type="text"
name="title"
value={title}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<label>Content</label>
<textarea
type="text"
name="body"
rows="15"
value={body}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<button className="btn btn-primary" type="submit">
Submit
</button>
</div>
</form>
</div>
);
}
}
export default NewPost;
App.js:
import React from "react";
import NavBar from "./components/layout/navbar";
import store from "./store";
import { Provider } from "react-redux";
import Dashboard from "./components/posts/dashboard";
import NewPost from "./components/posts/form";
import {
HashRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Router>
<React.Fragment>
<div className="container">
<NavBar />
<Switch>
<Route exact path="/" component={Dashboard}></Route>
<Route exact path="/new" component={NewPost}></Route>
</Switch>
</div>
</React.Fragment>
</Router>
</Provider>
);
}
}
export default App;
Issue is not related to code. I created new react application and moved all my code now everything is working fine.

How to use Link in React?

I am currently working on the react project which is a login-signup app using reactstrap. But I'm facing a problem when I use Link in the signup component in order to link the login component. Please help me to solve this problem.
component/signup.js:
import React, { Component } from 'react'
import {Link} from 'react-router-dom'
import '../App.css';
import {Button , Form, FormGroup, Label, Input} from 'reactstrap'
export class signup extends Component {
render() {
return (
<Form className="login-form App">
<h4 className="font-weight-bold text-center"> Sign Up Form</h4>
<FormGroup>
<Label>Full Name</Label>
<Input type="text" placeholder="Full Name"></Input>
</FormGroup>
<FormGroup>
<Label>Email</Label>
<Input type="email" placeholder="Email Address"></Input>
</FormGroup>
<FormGroup>
<Label>Password</Label>
<Input type="password" placeholder="Password"></Input>
</FormGroup>
<Button type="submit" className="btn-primary btn-lg btn-block">Sign Up</Button>
<p>Already Signup, <Link to ="/Login">Login</Link></p>
</Form>
)
}
}
export default signup
component/login.js:
import React, { Component } from 'react'
import '../App.css';
import {Button , Form, FormGroup, Label, Input} from 'reactstrap'
export class Login extends Component {
render() {
return (
<Form className="login-form App">
<h4 className="font-weight-bold text-center"> Login Form</h4>
<FormGroup>
<Label>Email</Label>
<Input type="email" placeholder="Email Address"></Input>
</FormGroup>
<FormGroup>
<Label>Password</Label>
<Input type="password" placeholder="Password"></Input>
</FormGroup>
<Button type="submit" className="btn-primary btn-lg btn-block">Login</Button>
</Form>
)
}
}
export default Login
App.js:
import React, { Component } from 'react'
import Signup from './component/signup'
import './App.css';
class App extends Component {
render() {
return (
<Signup />
)
}
}
export default App
You need to define the Login route in your App.js:
import React, { Component } from 'react'
import Signup from './component/signup'
import Login from './component/login' //Login should also be imported
import './App.css'
import { BrowserRouter as Router, Route } from "react-router-dom"//Router
class App extends Component {
render() {
return (
<Router> {/* Creating applications routes */}
<Route exact path="/" component={Signup} /> {/*Signup Route*/}
<Route exact path="/Login" component={Login} /> {/*Login Route*/}
</Router>
)
}
}
export default App
Notice I defined your signup on the root of your application (/). You can point it to wherever you want and you may need to define other routes in your App.js
Your code is missing some important part:
Link component are always wrapped up with Router component
In order to Link the component you have a Switch component containing the Route component.
Below is a sample code to use Link, Route, Router & Switch. Hope this will help
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Route, Link, BrowserRouter as Router, Switch } from "react-router-dom";
import "./styles.css";
const User = ({ match }) => {
console.log(match);
return <h1>User: {match.params.id}</h1>;
};
class Users extends Component {
render() {
return (
<div>
<h1>Users</h1>
<h2>Select a user</h2>
<li>
<Link to="/user/1">user 1</Link>
</li>
<li>
<Link to="/user/2">user 2</Link>
</li>
<li>
<Link to="/user/3">user 3</Link>
</li>
<Route path="/user/:id" component={User} />
</div>
);
}
}
class Contact extends Component {
render() {
return (
<div>
<h1>Contact</h1>
</div>
);
}
}
function App() {
return (
<div>
<h1>Home</h1>
</div>
);
}
function NotFound() {
return <h1>Not Found</h1>;
}
const routing = (
<Router>
<div>
<ul>
<li>
<Link to="/">home</Link>
</li>
<li>
<Link to="/users">users</Link>
</li>
<li>
<Link to="contact">contact</Link>
</li>
</ul>
<Switch>
<Route exact path="/" component={App} />
<Route path="/users" component={Users} />
<Route path="/contact" component={Contact} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
const rootElement = document.getElementById("root");
ReactDOM.render(routing, rootElement);
CodeSandbox demo: working code demo
When you want to use the Link component to define which links in your component. You must use at the highest level of your Component tree the BrowserRouter component from react-router-dom
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import { React } from 'react';
import { Signup } from './component/signup';
import { Login } from './component/Login';
export default function App(props) {
return (
<div>
// Any code goes here
<Router>
<Switch>
<Route exact={true} path="/login" component={Login}/>
<Route exact={true} path="/signup" component={Login}/>
<Redirect path="/login" />
</Switch>
</Router>
// Any code goes here
</div>
)
}
After you have use Router to define which component is rendered on given path in the Highest component in the component tree you can use Link in any Child component

Categories