How to go from one page to another - javascript

I have a SignIn form and I want to create the SignUp link.
On link click I want to open SignUp page.
I have created index.js nothing in that another app.js I wrote SignIn logic.
Here is the Code :
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
}
validateForm() {
return this.state.email.length > 0 && this.state.password.length > 0;
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
}
handleSubmit = event => {
event.preventDefault();
}
render(){
return (
<div class="container">
<form onSubmit={this.handleSubmit}>
<div id="login">
<div class="form-group">
<h2 align="center">Login Form</h2>
Email :
<input type="email" id="email" value={this.state.email} onChange={this.handleChange} class="form-control" placeholder="Email Address"/><br/>
Password :
<input type="password" id="password" value={this.state.password} onChange={this.handleChange} class="form-control" placeholder="Password"/><br/>
Sign Up<br/><br/>//here I want to change
<button id="send" disabled={!this.validateForm()} class="btn btn-default">Sign In</button>
</div>
</div>
</form>
</div>
);
}
}
export default App;
I have added the Anchor tag in that but it won't work . I want to create the link in place of anchor tag in that onclick the signup page will open. I have started to create signUp page also
here is my code:
import React, { Component } from 'react';
import './App.css';
export default class Signup extends Component {
render(){
return (
<div class ="container">
<form>
<div id="signup">
<div class="form-group">
First Name :
<input type="text" id="first" class="form-control" placeholder="First Name"/><br/>
Last Name :
<input type="text" id="last" class="form-control" placeholder="Last Name"/><br/>
Email :
<input type="email" id="email" class="form-control" placeholder="Email"/><br/>
Password :
<input type="password" id="password" class="form-control" placeholder="Password"/><br/>
Re-enter Password :
<input type="password" id="confirm" class="form-control" placeholder="Confirm Password"/><br/>
<button id="save">Save</button>
</div>
</div>
</form>
</div>
);
}
}
How do I create the routes to go from one page to another?

Use Link instead of a tag:
import { Link } from 'react-router-dom';
.
.
<Link to='/signup'>Sign Up</Link>
EDIT: I'm updating the code for your solution for now, but I need you to understand you might not be getting such a solution whenever you post questions here. Stack Overflow requires you to read through any documentation and do extensive research before asking any question.
I need you to look at the code below and fully understand it by reading the React Router docs before copy-pasting it.
Change your App.js to:
import React, { Component } from 'react';
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom';
import Signup from './Signup';
import './App.css';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
}
validateForm() {
return this.state.email.length > 0 && this.state.password.length > 0;
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
}
handleSubmit = event => {
event.preventDefault();
}
render() {
return (
<div class ="container">
<form onSubmit={this.handleSubmit}>
<div id="login">
<div class="form-group">
<h2 align="center">Login Form</h2>
Email :
<input type="email" id="email" value={this.state.email} onChange={this.handleChange} class="form-control" placeholder="Email Address"/><br/>
Password :
<input type="password" id="password" value={this.state.password} onChange={this.handleChange} class="form-control" placeholder="Password"/><br/>
<Link to="/signup">Signup</Link>
<button id="send" disabled={!this.validateForm()} class="btn btn-default">Sign In</button>
</div>
</div>
</form>
</div>
)
}
}
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/' component={Login}/>
<Route path='/signup' component={Signup}/>
</Switch>
</Router>
);
}
}
export default App;
and your expected working is achieved. Let me know if that solved by accepting this answer, or comment below.
P.S: React Router docs: https://reacttraining.com/react-router/web/guides/philosophy
Happy Coding!

If you are using react-router 4.x and above, then import it like this
import {Link} from 'react-router-dom'
For react-router versions < 4.x
import {Link} from 'react-router';
And in your return, you can link to another page by
<Link to="/signup">Signup</Link>

Related

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

I'm trying to create a sign up form with an input for a users address. The address input uses the google autocomplete address api.
I'd like to be able to keep it as a Formik field, so I can use Yup validation on it.
The address input component looks like
// Google.jsx
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
/* global google */
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.autocompleteInput = React.createRef();
this.autocomplete = null;
this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}
componentDidMount() {
this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
{"types": ["address"]});
this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}
handlePlaceChanged(){
const place = this.autocomplete.getPlace();
console.log(place);
}
render() {
return (
<Field ref={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder="" />
);
}
}
export default SearchBar;
And my Form component looks like:
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import SearchBar from "./Google";
const LoginSchema = Yup.object().shape({
fName: Yup.string().required("Please enter your first name"),
address: Yup.string().required("invalid address"),
});
class Basic extends React.Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-lg-12">
<Formik
initialValues={{
fName: "",
postal: "",
}}
validationSchema={LoginSchema}
onSubmit={(values) => {
console.log(values);
console.log("form submitted");
}}
>
{({ touched, errors, isSubmitting, values }) =>
!isSubmitting ? (
<div>
<div className="row mb-5">
<div className="col-lg-12 text-center">
<h1 className="mt-5">LoKnow Form</h1>
</div>
</div>
<Form>
<div className="form-group">
<label htmlFor="fName">First Name</label>
<Field
type="text"
name="fName"
className={`mt-2 form-control
${touched.fName && errors.fName ? "is-invalid" : ""}`}
/>
<ErrorMessage
component="div"
name="fName"
className="invalid-feedback"
/>
</div>
<div className="form-group">
<label htmlFor="address">Address</label>
<Field name="address" component={SearchBar} placeholder="" />
<ErrorMessage
component="div"
name="address"
className="invalid-feedback"
/>
</div>
<button
type="submit"
className="btn btn-primary btn-block mt-4"
>
Submit
</button>
</Form>
</div>
) : (
<div>
<h1 className="p-3 mt-5">Form Submitted</h1>
<div className="alert alert-success mt-3">
Thank for your connecting with us.
</div>
</div>
)
}
</Formik>
</div>
</div>
</div>
);
}
}
export default Basic;
This returns an error of "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?".
Which is coming from my address input component at: <Field ref={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder="" />
Everything else is working, I just need to get past this last hurdle and I'll be good from here.
I will begin looking into the docs, but I'm unfortunately in a rush to get this done so I figured I'd try my luck here!
Any help is greatly appreciated! Thank you!
The Field component does allow you to get access to the underlying element, but not via ref. You need to pass it to innerRef instead.
<Field innerRef={this.autocompleteInput} id="autocomplete" type="text" name="address" placeholder=""/>
See documentation of Field here: https://formik.org/docs/api/field#innerref

Error of send data to blockchain application in React js

I have blockchain application and created Reactjs interface to send data from user to application but when i enter data and try send it get error as follow , any one can help me?
The error is :
XHR POST http://localhost:3000/api/MedicalRecord
[HTTP/1.1 422 Unprocessable Entity 19ms]
The App.js file as follow
import React, { Component } from 'react';
import PostForm from './PostForm'
function App() {
return (
<div className="App">
<PostForm></PostForm>
</div>
);
}
export default App;
The PostForm.js file as follow
import React, { Component } from 'react'
import axios from 'axios'
class PostRecords extends Component {
constructor(props){
super(props)
this.state = {
record_Id: "",
patient: "",
doctor: "",
description: "",
prescription: ""
}
}
handleChange =(e) =>{
this.setState({
[e.target.name]: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
axios.post('http://localhost:3000/api/MedicalRecord')
.then(response =>{
console.log(response)
})
}
render() {
const {record_id, patient, doctor, description, prescription} = this.state
return (
<div>
<form onSubmit={this.handleSubmit}>
<div>
<label>record_id :</label>
<input
type='text'
name ='record_id'
value={record_id}
onChange={this.handleChange}
></input>
</div>
<div>
<label>patient :</label>
<input
type='text'
name ='patient'
value={patient}
onChange={this.handleChange}
></input>
</div>
<div>
<label>doctor :</label>
<input
type='text'
name ='doctor'
value={doctor}
onChange={this.handleChange}
></input>
</div>
<div>
<label>description :</label>
<input
type='text'
name ='description'
value={description}
onChange={this.handleChange}
></input>
</div>
<div>
<label>prescription :</label>
<input
type='text'
name ='prescription'
value={prescription}
onChange={this.handleChange}
></input>
</div>
<button type='submit'>Submit Now</button>
</form>
</div>
)
}
}
export default PostRecords

React setState hook keeps resetting and rendering the page twice

I have an react app Form component split into Login and Signup forms. It is supposed to render the Signup by default but switch to Login if login is button is clicked. When login button is clicked, the page switches to the Login form very briefly before switching back to the Signup form. I don't know what is causing this. I have tried placing const [page, setPage] = setState("signup") in the parent App and passing setPage as a prop along with page. This produced the same results. I believe this issue is similar to this one but that was not resolved.
Here is the app:
import Form from "./components/Signup-Form.js";
function App() {
return (
<div className="App">
<h1>Welcome</h1>
<Form />
</div>
);
}
export default App;
and Signup-Form.js:
import React from "react";
import { useState, useEffect } from "react";
import "./Forms.css";
import { InputField, Buttons } from "./Inputs";
function Form() {
const [page, setPage] = useState("signup");
const pageLabel = page;
let Signup = () => {
function toLogin() {
setPage("login");
}
return (
<form action="" method="get" className="form">
<div className="input-container">
<InputField name="Company Name" id="comp-name" type="text" />
<InputField name="Company ID" id="comp-id" type="text" />
<InputField name="Username" id="username" type="text" />
<InputField name="Email" id="email" type="email" />
<InputField name="Password" id="password" type="password" />
<InputField name="Confirm Password" id="confirm-password" type="password" />
</div>
<div className="btns">
<Buttons name="Sign Up" id="signup-btn" type="submit" cls="success" />
<Buttons name="Log In" id="login-btn" type="button" cls="success" alt="true" onClick={toLogin} />
</div>
</form>
);
};
let Login = () => {
function toSignup() {
setPage("signup");
}
return (
<form action="" method="get" className="form">
<div className="input-container">
<InputField name="Company ID" id="comp-id" type="text" />
<InputField name="Password" id="password" type="password" />
</div>
<div className="btns">
<Buttons name="Log In" id="login-btn" type="submit" cls="success" />
<Buttons name="Sign Up" id="signup-btn" type="submit" cls="success" alt onClick={toSignup} />
</div>
</form>
);
};
let form = (formType) => (
<div className="outer-wrapper">
<div className="form-wrapper">
<label className="form-title">{pageLabel}</label>
{formType}
</div>
</div>
);
if (page === "signup") {
const signup = Signup();
return form(signup);
} else if (page === "login") {
const login = Login();
return form(login);
}
}
export default Form;
The reason why after you click on Login button and get Login page and the page immediately re-renders and you get the Signup page is conditional render in your example. Right after clicking on Login button your state still previous and for this reason after click you get the main (Signup) page.
Suggest to change the structure render into smth like this:
...
return (
<div className="outer-wrapper">
<div className="form-wrapper">
<label className="form-title">{pageLabel}</label>
{page === "signup" && Signup()}
{page === "login" && Login()}
</div>
</div>
);
Here is the example in an action - https://codesandbox.io/s/smoosh-water-6jj18?file=/src/App.js

Why is my checkbox not displaying in reactjs?

I am trying to display a checkbox when the add button is clicked but it refuses to display. Take a look at the addTask() function and you will see what I am trying to do. Thank you, in advance!
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask()}>Add</button>
</div>
</div>
</div>
</div>
);
}
addTask() {
var tasks = document.getElementById('task');
localStorage.setItem('user-task', tasks);
return(
<input type="checkbox" label={localStorage.getItem('user-task')} />
)
}
}
export default MainPage;

Error(Cannot post on rendering a page) in Reactjs and node JS

I am building a registration page for my project and encountered an error Cannot POST / on rendering the web page .Earlier i also have made a login page which is working correctly by using almost same syntax. Here are my files.
1)Registration.js
import React,{Component} from 'react';
import Axios from 'axios';
class Registration extends Component{
constructor(props)
{
super(props);
this.state={
name:"",
gender:"",
city:"",
state:"",
email:"",
password:""
};
}
render(){
return(
<div class="main">
<h1>Sign up</h1>
<div className="container">
<div className="sign-up-content">
<form method="POST" class="signup-form" onSubmit={this.onSubmit}>
<h2 className="form-title">Register yourself below:-</h2>
<div className="form-textbox">
<label for="name">Full name</label>
<input type="text" name="name" id="name" value={this.state.name} onChange={this.onChangeName}/>
</div>
<div className="form-textbox">
<label for="Gender">Gender</label>
<input type="text" name="gender" id="gender" value={this.state.gender} onChange={this.onChangeGender}/>
</div>
<div className="form-textbox">
<label for="City">City</label>
<input type="text" name="city" id="city" value={this.state.city} onChange={this.onChangeCity}/>
</div>
<div className="form-textbox">
<label for="State">State</label>
<input type="text" name="State" id="State" value={this.state.state} onChange={this.onChangeSate}/>
</div>
<div className="form-textbox">
<label for="email">Email</label>
<input type="email" name="email" id="email" value={this.state.email} onChange={this.onChangeEmail}/>
</div>
<div className="form-textbox">
<label for="pass">Password</label>
<input type="password" name="pass" id="pass" value={this.state.password} onChange={this.onChangePassword}/>
</div>
{/* <div className="form-group">
<input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
<label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in Terms of service</label>
</div> */}
<div className="form-textbox">
<input type="submit" name="submit" id="submit" class="submit" value="Create account" />
</div>
</form>
<p className="loginhere">
Already have an account ? Log in
</p>
</div>
</div>
</div>
);
};
onChangeName=(e)=>{
this.setState({
name:e.target.value
});
};
onChangeGender=(e)=>{
this.setState({
gender:e.target.value
});
};
onChangeCity=(e)=>{
this.setState({
city: e.target.value
});
};
onChangeSate=(e)=>{
this.setState({
state:e.target.value
});
};
onChangeEmail=(e)=>{
this.setState({
email:e.target.value
});
};
onChangePassword=(e)=>{
this.setState({
password:e.target.value
});
};
onSubmit=(e)=>{
console.log("inside on submit");
const vals={...this.state};
Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
};
}
export default Registration;
2)App.js
import React from 'react';
import Login from './Login';
import Registration from './Registration';
const App=()=>(
<Registration />
);
export default App;
3)index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('root'));
4)Node js server (server.js)
const express=require('express');
const bodyParser=require('body-parser');
const mysql=require('mysql');
const cors=require('cors');
const app=express();
app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
const con=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'reactProject'
});
// app.post('/login',(request,resposne)=>{
// const email=request.body.email;
// const password=request.body.password;
// console.log(email+" "+password)
// const sql='select * from login where email = "'+email+'" and password="'+password+'" ';
// con.query(sql,(err,result)=>{
// if(result.length)
// {
// console.log(result);
// console.log("signed in");
// }
// else{
// console.log(result);
// console.log("Not signed");
// }
// });
// });
app.post('/register',(request,resposne)=>{
const name=request.body.name;
const gender=request.body.gender;
const city=request.body.city;
const state=request.body.state;
const email=request.body.email;
const password=request.body.password;
console.log(name+" "+gender);
const sql=`insert into register(name,gender,city,state,email,password) values('${name}','${gender}','${city}','${state}','${email}','${password}')`;
con.query(sql,(result,error)=>{
console.log(result);
});
});
app.listen(4200,()=>{
console.log("Server at 4200");
});
The above files are server.js,App.js,index.js,Registration it might be that whenever i click on submit it doesnot go inside onSubmit function .
In React, when you create a custom function to handle form submission, you need to call event.preventDefault(). The problem you are getting is due to the fact that your HTML is trying to send a post request when you submit the form, which you haven't set it up to do.
Here is a similar question where you can find more detailed information: React - Preventing Form Submission.
So, a way to fix this would be to change your onSubmit function to something like this:
onSubmit=(e)=>{
console.log("inside on submit");
e.preventDefault();
const vals={...this.state};
Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
};

Categories