Trouble rendering correct html page in react - javascript

I have been trying to render the correct HTML page using react. However, for some reason when I click the navigation button link in my signin page, I do not get directed to the right page, it is the same html. I am using react-router-dom' but it still does not render my sign up page.
My code looks like
App.js
import React, { Component } from 'react';
import cupcake from './images/cupcake.png';
import './App.css';
import {BasicExample} from './route.js'
import { Link } from 'react-router-dom'
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
class App extends Component {
render() {
return (
<div className="App">
<div className = "loginBox">
<div className = "glass">
<img src= {cupcake} className = "user" />
<h3>Sign in Here</h3>
<form>
<div className = "inputBox">
<input type="text" name="" placeholder="Username" />
<span><i className="fa fa-user" aria-hidden="true"></i></span>
</div>
<div className = "inputBox">
<input type="password" name="" placeholder="Password" />
<span><i className="fa fa-lock" aria-hidden="true"></i></span>
</div>
<input type="submit" name="" value="Login" />
</form>
Forgot Passwordk?
<br />
<Router>
<Link to="/Signup">Signup??</Link>
</Router>
</div>
</div>
</div>
);
}
}
export default App;
Signup.js
import React, { Component } from 'react';
import cupcake from './images/cupcake.png'
import './App.css';
export class Signup extends Component {
render() {
return (
<div className="ignup">
<div className = "loginBox">
<div className = "glass">
<img src= { cupcake} className = "user" />
<h3>Signup Here!</h3>
<form>
<div className = "inputBox">
<input type="text" name="" placeholder="Username" />
<span><i className="fa fa-user" aria-hidden="true"></i></span>
</div>
<div className = "inputBox">
<input type="password" name="" placeholder="Password" />
<span><i className="fa fa-lock" aria-hidden="true"></i></span>
</div>
<input type="submit" name="" value="Login" />
</form>
Login!
</div>
</div>
</div>
);
}
}
export default Signup
route.js
import React from 'react';
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
const Signup = require('./Signup.js');
const BasicExample = () => (
<Router>
<div>
<Route path="/Signup" component={Signup}/>
</div>
</Router>
)
export default BasicExample
Thank you so much, any advice will be appreciated!

One thing is that you use BrowserRouter here and there. It should be top-level-component, meaning it should wrap your whole app and used only once.
So if your App component is the main component where everything starts then do:
class App extends Component {
render() {
return (
<Router>
<div className="App">
...
...
</div>
</Router>
);
}
}
And remove BrowserRouter from anywhere else.
Another thing I believe (could be wrong) that you cannot use import and require together. So change
const Signup = require('./Signup.js');
to
import Signup from './Signup';

Related

React Js navigate between pages using Navigate inside the button click event [duplicate]

This question already has an answer here:
Problem in redirecting programmatically to a route in react router v6
(1 answer)
Closed 11 months ago.
I am using latest version of the react js. I want to navigate the add page to after login. here is the my code.
import React,{Component} from 'react';
import { variables } from '../../Variables';
import { Navigate } from 'react-router-dom';
export class Login extends Component{
constructor(props){
super(props);
this.state={
login:[],
name:"",
password:"",
redirect: false
}
}
changelogindetailsname = (e)=>{
this.setState({name:e.target.value})
}
changelogindetailspass = (e)=>{
this.setState({password:e.target.value})
}
loginClick(){
fetch(variables.API_URL+'login',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
name:this.state.name,
password:this.state.password
})
})
.then(res=>res.json())
.then((result)=>{
alert(result);
const navigate = Navigate();
navigate("/add" , { replace: "/" } );
},(error)=>{
alert('Faild');
})
}
render(){
const{
name,
password
}=this.state;
return(
<div>
<center>
<h1></h1>
<hr/>
<h3>Welcome Back !</h3>
<p></p>
<div className="container">
<br/>
<br/>
<br/>
<div className="row">
<div className="col">
</div>
<div className="col">
</div>
<div className="col-4">
<style>{"\ .rr{\ float:left;\ }\ "} </style>
<style>{"\ .bb{\ float:right;\ }\ "} </style>
<div className="mb-3">
<label className="form-label rr d-flex"> Username</label>
<div className="input-group input-group-lg">
<input type="text" className="form-control " id="formGroupExampleInput" placeholder="Username"
value={name}
onChange={this.changelogindetailsname}/>
</div>
</div>
<div className="mb-3">
<label className="form-label rr d-flex">Password</label>
<div className="input-group input-group-lg">
<input type="password" className="form-control" id="formGroupExampleInput2" placeholder="Password"
value={password}
onChange={this.changelogindetailspass}/>
</div>
</div>
<div className="d-flex mb-3">
Forgot your password?
</div>
<div className="col">
<div className="form-check rr">
<input className="form-check-input" type="checkbox" value="" id="flexCheckDefault"/>
<label className="form-check-label" htmlFor="flexCheckDefault">
Remember me
</label>
</div>
</div>
<div className="col">
<button type="button" className="btn btn-success bb"
onClick={()=>this.loginClick()} navigate="/Add.js" >Login</button>
</div>
<br/>
<br></br>
<hr/>
<p>Don't have an account?</p>
<div className="mb-3">
<button type="button" className="btn btn-light d-flex"
href="Add.js" >Sign up for Muessoze</button>
</div>
</div>
<div className="col">
</div>
<div className="col">
</div>
</div>
</div>
</center>
</div>
)
}
}
This is compile without error but the runtime browser console get this error
Uncaught (in promise) TypeError: Cannot destructure property 'to' of '_ref2' as it is undefined.
at Navigate (index.tsx:165:1)
at Login.js:44:1
This is the App.js file code
import { BrowserRouter, Route, Routes } from 'react-router- dom';
import './App.css';
import { Login } from './components/Login/Login';
import { Add } from './components/Login/Add';
function App() {
return (
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Login/>}/>
<Route exact path="/add" element={<Add/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
I have no idea what to do, I tried several times but problem is the same. I think passing parameters is the reason for this error. but still I have no solution for this. please help me.
EDIT ( After OP clarified he is using a class Component ):
Since you are using a class component, you can't use Hooks (Please switch to function components, most react class based code is legacy code! ), but you can decorate your Component with a HOC and pass navigate to it as a prop, we answered a few hours ago to a very similar question :
HOC:
const withNavigate = Component => props => {
const navigate = useNavigate();
const params = useParams();
return <Component {...props} params={params} navigate={navigate} />;
}
const LoginWithNavigate = withNavigate(Login);
Then in your Login Component you can just do this.props.navigate("/") to navigate.
Delete const navigate = Navigate();
Navigate is a React Component you can't use it like that, to use navigate like that you need to use useNavigate hook .
Import {useNavigate} from "react-router-dom"
then inside your React component:
const navigate = useNavigate()
Now it should work, just change replace prop to a boolean value.

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'push') , using useHistory

I am new to the react js, while trying to fetch the page from different components using (trying to fetch dashboard component from loginform component and the loginform component is inside the landing page) history.push() I am getting this error.
(app.js)
import React from "react";
import { BrowserRouter as Router,Route,Switch } from "react-router-dom";
import LandingPage from "./Pages/LandingPage/LandingPage";
import DashBoard from "./Pages/Dashboard/dashBoard";
export default function App(){
return(
<Router>
<Switch>
<Route exact path="/" component={LandingPage} />
<Route exact path="/dashboard" component={DashBoard}/>
</Switch>
</Router>
);
}
(login page)
here I m facing the issue in login method
import React, { useRef, useState,useEffect } from 'react';
import { gsap } from 'gsap';
import $ from 'jquery';
import swal from 'sweetalert';
import {useHistory,withRouter} from 'react-router-dom';
import './LF.css';
import LoginLogo from './zmtLogo.png';
var LoginForm = (props) => {
let history = useHistory();
var Login = async ()=>{
if(LoginData.email !== '' & LoginData.pass!== ''){
history.push("/dashboard")
}else{
swal({
title: "Incomplite fillup",
icon: "warning"
});
}
}
return (
<>
<div className="l_main" ref={LOGbox}>
<div className="login">
<p>Login Here!</p>
<div className="fillup">
<i className="far fa-envelope"></i>
<input onChange={LoginFillup} value={LoginData.email} id="userid" name="userid" type="text" placeholder="Email" />
</div>
<div className="fillup">
<i className="fas fa-lock"></i>
<input onChange={LoginFillup} value={LoginData.pass} id="pass" name="pass" type="password" placeholder="password" />
<i className="fas fa-eye" id="eye"></i>
</div>
<button onClick={Login}>Login</button>
<p id="signup">don't have an account?<span id="click_1" onClick={LeftSlider}>create</span> </p>
<p id="fo_p">Forget password</p>
</div>
{/* <!-- .................................................................................................. --> */}
<div className="signup">
<p>Signup Here!</p>
<div className="fillup">
<i className="fas fa-users"></i>
<input onChange={signupFillup} value={SignUpData.userName} id="user_name" name="user_name" type="text" placeholder="name" />
</div>
<div className="fillup">
<i className="far fa-envelope"></i>
<input onChange={signupFillup} value={SignUpData.email} id="user_em" name="user_em" type="text" placeholder="email" />
</div>
<div className="fillup">
<i className="fas fa-lock"></i>
<input onChange={signupFillup} value={SignUpData.pass} id="user_pass" name="user_pass" type="password" placeholder="password" />
</div>
<div className="fillup">
<i className="fas fa-lock"></i>
<input onChange={signupFillup} value={SignUpData.pass2} id="user_pass_2" name="user_pass_2" type="password" placeholder="password(re type)" />
</div>
<button onClick={Signup}>Register</button>
<p id="login">Already have an account.<span id="click_2" onClick={RightSlider}>login</span> </p>
</div>
{/* <!-- ................................................................................................--> */}
<div className="slider">
<div className="img_area">
<div className="close_tab" onClick={props.closefunction}>
close
</div>
<div className="img_sec">
<img src={LoginLogo} alt="" />
</div>
</div>
</div>
</div>
</>
)
};
export default LoginForm;
I'm not entirely sure why you've structured your code as such, but the LandingPage is rendering the LoginForm into a separate DOM element rendered into a reactDom.render and thus isn't rendered within the routing context. history is indeed undefined.
reactDom.render(
<LoginForm closefunction={ClosePopup} />,
document.getElementsByClassName("Lpopup")[0]
);
Normally you would create a React portal, though, after inspecting the landing page logic I don't think this is necessary and suggest the following to fix:
LandingPage
Convert the PopDisplay state to a boolean to show/hide the "modal", and conditionally render the "Lpopup" div and LoginForm.
const [PopDisplay, setPopDisplay] = useState(false);
const DisplayPopup = () => {
setPopDisplay(true);
};
const ClosePopup = () => {
setPopDisplay(false);
};
...
{PopDisplay && (
<div className="Lpopup" style={{ display: "flex" }}>
<LoginForm closefunction={ClosePopup} />
</div>
)}
Now that LoginForm is being rendered within the same app it should have access to the routing context and the useHistory hook should return a defined history object.
In react router dom v6 useHistory has been replace by usenavigate hook.
so do
import {useNavigate} from 'react-router-dom'
const App=()=>{
const history=useNavigate()
return <>....</>
}
https://reactrouter.com/docs/en/v6/getting-started/overview
check out this
Or else downgrade the version of react-router-dom to make use of usehistory hook

TypeError: setOpenModal is not a function

I am trying to make a login modal popup which will show on click of a button inside of a navbar. However, I am getting below error:
TypeError: setOpenModal is not a function
Even after looking at many threads here, I am unable to understand what is causing the error in my case. Below is my code:
Navbar.js:
import React, { useState } from "react";
import { Link } from "react-router-dom";
import "./Navbar.css";
import Login from "./Login";
function Navbar() {
const [openModal, setOpenModal] = useState(false);
const showModal = () => {
setOpenModal(true);
};
return (
<nav className="navbar">
<div className="nav-div">
<Link to="/" className="nav-logo">
<i class="fas fa-hamburger"></i>Hungermania
</Link>
<div className="nav-form">
<form>
<input
className="nav-search"
type="search"
placeholder="Search for your favorite restaurant, cuisine or a dish"
></input>
<button className="btn-search">Search</button>
</form>
</div>
<ul>
<li className="nav-item">
<button className="login-btn nav-link" onClick={showModal}>
Login
</button>
{openModal && <Login setOpenModal={setOpenModal} />}
</li>
<li className="nav-item">
<button className="signup-btn nav-link">Sign Up</button>
</li>
</ul>
</div>
</nav>
);
}
export default Navbar;
Login.js:
import React from "react";
import "./Login.css";
function Login({ setOpenModal }) {
const hideModal = () => {
setOpenModal(false);
};
return (
<div className="modalBackground">
<div className="modalContainer">
<div className="titleclosebtn">
<button onClick={hideModal}>×</button>
</div>
<div className="title">
<h1>Login</h1>
</div>
<div className="body">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" required />
<br />
<br />
<label for="phone">Phone No:</label>
<input type="number" placeholder="Phone No." required />
<br />
<br />
<label for="email">Email Id:</label>
<input type="email" placeholder="Email#domain.com" required />
<br />
<br />
<div className="footer">
<button type="submit" class="btn-signup">
SIGN UP
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default Login;
There's nothing wrong with ur code, so it was prob cash or something.
restarting server should stop accusing that error.
Normally when stupid errors like this happens, i just comment that part that is accusing error, wait refresh and uncomment, that works too instead of always restarting server.
{openModal && <Login setOpenModal={setOpenModal} />}
this part of the code. You are passing down a prop named setOpenModal and you are passing down setOpenModal. You cannot pass down the setter of your state. You can either pass down variables or functions with props. So create a function, in that function you can use setOpenModal and then pass that function down like this:
const someFunction=(value)=>{
setOpenModal(value);
}
{openModal && <Login whatEverName={someFunction} />}

Why I cannot type continuously in react Input field when passing values to another component using props

I am trying to pass values through props from one component to another.
Parent component is InstructorLoginForm and child component is InstructorLoginFormComponent
Everything works fine but the problem is I cannot type in input text field continuously
I try to type username, it types one letter and then it kind loses the focus into the input field, so I have to again click on the input field and type another(single) letter and again focus loses
This is same for the password field too.
Hers is my parent component InstructorLoginForm.jsx
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InstructorProfile from "./instructor-profile";
import InstructorLoginFormComponent from "./instructor-login-form-component";
export default class InstructorLoginForm extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: ""
};
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.handleOnClick = this.handleOnClick.bind(this);
}
onChangeUsername(e) {
this.setState({
username: e.target.value
});
}
onChangePassword(e) {
this.setState({
password: e.target.value
});
}
handleOnClick (){
e.preventDefault();
this.props.history.push(`/instructor/${this.state.username}`);
}
render() {
return (
<Router>
<Switch>
<Route
exact
path="/login"
component={props => (
<InstructorLoginFormComponent
{...props}
username = {this.state.username}
password = {this.state.password}
handleOnClick = {this.handleOnClick}
onChangeUsername = {this.onChangeUsername}
onChangePassword = {this.onChangePassword}
/>
)}
/>
<Route
path={"/instructor/:instructorId"}
component={InstructorProfile}
/>
</Switch>
</Router>
);
}
}
And here is my child component InstructorLoginFormComponent.jsx
import React, { Component } from "react";
import { Link } from "react-router-dom";
export default class InstructorLoginFormComponent extends Component {
constructor(props) {
super(props);
}
componentDidMount(){
console.log(this.props);
}
render() {
return (
<div className="container h-100" style={{ marginTop: 100 }}>
<div className="d-flex justify-content-center h-100">
<div className="user_card bg-dark">
<div className="d-flex justify-content-center">
</div>
<div
className="d-flex justify-content-center form_container"
style={{ marginTop: 0 }}
>
<form>
<div className="input-group mb-3">
<div className="input-group-append">
<span className="input-group-text bg-info">
<i className="fa fa-user" />
</span>
</div>
<input
value={this.props.username}
onChange={this.props.onChangeUsername}
type="text"
name="username"
className="form-control input_user"
placeholder="username"
/>
</div>
<div className="input-group mb-2">
<div className="input-group-append">
<span className="input-group-text bg-info">
<i className="fa fa-lock" />
</span>
</div>
<input
value={this.props.password}
onChange={this.props.onChangePassword}
type="password"
name="passwordbutton"
className="form-control input_user"
placeholder="password"
/>
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id="customControlInline"
/>
<label
className="custom-control-label"
htmlFor="customControlInline"
style={{ color: "#ffffff" }}
>
Remember me
</label>
</div>
</div>
</form>
</div>
<div className="d-flex justify-content-center mt-3 login_container">
<button
// to={`/instructor/${this.props.username}`}
onClick={this.props.handleOnClick}
type="button"
className="btn login_btn bg-info"
>
Login
</button>
</div>
</div>
</div>
</div>
);
}
}
Can someone help me why this happens and how to resolve it?
When you type text, the state of the parent component updates and render function calls again. You used
<Route component={...} />
it calls React.createElement at every render, so old child component unmounts and router creates new instance, focus loses.
To fix this issue use
<Route render={<InstructorLoginFormComponent ... />} />
it also provides {match, location, history} props to child, but does not unmount it when parent state changed.
Sorry to put it this way, but this is poor architecture along with a few mistakes in syntax.
You should have all routes in your App.js file and everything else in your Component file (should actually be a Container.js file and a Component.js file, but for another time).
You only need one onChange event (note change to the function structure).
The below behaves as it should.
Please note the handleOnClick should have (e), that should be throwing an error.
Please note password name in the input has been corrected to password, from password button
App.js;
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InstructorProfile from "./instructor-profile";
import InstructorLoginFormComponent from "./instructor-login-form-component";
export default class App extends Component {
render() {
return (
<Router>
<Switch>
<Route
exact
path="/login"
component={InstructorLoginFormComponent }
/>
<Route
path={"/instructor/:instructorId"}
component={InstructorProfile}
/>
</Switch>
</Router>
);
}
}
and InstructorLoginFormComponent;
import React, { Component } from "react";
import { Link } from "react-router-dom";
export default class InstructorLoginFormComponent extends Component {
constructor(props) {
super(props)
this.state = {
username: "",
password: ""
}
this.onChange = this.onChange.bind(this)
this.handleOnClick = this.handleOnClick.bind(this)
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
handleOnClick (e) {
e.preventDefault()
this.props.history.push(`/instructor/${this.state.username}`)
}

render() {
const { username, password } = this.state
return (
<div className="container h-100" style={{ marginTop: 100 }}>
<div className="d-flex justify-content-center h-100">
<div className="user_card bg-dark">
<div className="d-flex justify-content-center">
</div>
<div
className="d-flex justify-content-center form_container"
style={{ marginTop: 0 }}
>
<form>
<div className="input-group mb-3">
<div className="input-group-append">
<span className="input-group-text bg-info">
<i className="fa fa-user" />
</span>
</div>
<input
value={username}
onChange={this.onChange}
type="text"
name="username"
className="form-control input_user"
placeholder="username"
/>
</div>
<div className="input-group mb-2">
<div className="input-group-append">
<span className="input-group-text bg-info">
<i className="fa fa-lock" />
</span>
</div>
<input
value={password}
onChange={this.onChange}
type="password"
name="password"
className="form-control input_user"
placeholder="password"
/>
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id="customControlInline"
/>
<label
className="custom-control-label"
htmlFor="customControlInline"
style={{ color: "#ffffff" }}
>
Remember me
</label>
</div>
</div>
</form>
</div>
<div className="d-flex justify-content-center mt-3 login_container">
<button
// to={`/instructor/${this.props.username}`}
onClick={this.props.handleOnClick}
type="button"
className="btn login_btn bg-info"
>
Login
</button>
</div>
</div>
</div>
</div>
);
}
}

React Component is blank in the webpage

I created a Reactjs app by create-react-app.
... but the components are not shown in the page, I think it is probably because App.js is not rendering the components?
Here is my code:
App.js
import React, { Component } from 'react';
import './App.css';
import login from "./containers/login/login";
class App extends Component {
render() {
return (
<div className="App">
<login/>
</div>
);
}
}
export default App;
/containers/login/login.js
import React, { Component } from 'react';
import "./login.css";
class login extends Component {
render() {
return (
<div className="headings">
<form action="">
Username <br/>
<input type="text" name="userrname" />
<br/>
Password <br/>
<input type="password" name="password" />
<br/>
<input type="submit" value="Login" />
</form>
</div>
);
}
}
export default login;
The component in the browser is like this:
<login></login>
Your own component need to start with a capital letter, or Babel will treat them as strings.
Rename the variable to Login and it will work.
import Login from "./containers/login/login";
class App extends Component {
render() {
return (
<div className="App">
<Login />
</div>
);
}
}

Categories

Resources