I am learning React now . I have made a page called as App.js which is a Login Page.I have navigated it to another page App2.js . The navigation process is being done , but I am not able to see the contents in that page .
Here is my Code:-
App.js
import React from "react";
import "./App.css";
//import './App2'
import { Navigate } from "react-router-dom";
function App() {
const [goToContact, setGoToContact] = React.useState(false);
if (goToContact) {
return <Navigate to="/App2" />;
}
return (
<div className="LoginPage">
<div className="topnav">
<h1 className="Heading">E-Commerce App</h1>
</div>
<div className="card">
<div className="container">
<h1 className="SignUp">Sign Up</h1>
<form>
<label for="email" className="email">
<b>Email</b>
</label>
<br />
<input type="email" name="email" placeholder="Enter your email" />
<br />
<label for="psw" className="Password">
<b>Password</b>
</label>
<br />
<input
type="password"
name="Password"
placeholder="Enter your password"
/>
<br />
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<br />
<input
type="password"
name="Repeat Password"
placeholder="Repeat Password"
/>
<br />
<input type="checkbox" name="Remember Me" className="remember" />
<label for="vehicle1"> Remember Me</label>
<br />
<div class="clearfix">
<button
type="button"
class="cancelbtn"
onClick={() => {
setGoToContact(true);
}}
>
Login
</button>
<button type="submit" class="signupbtn">
Sign Up
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default App;
App2.js
import React from "react";
function App2() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
export default App2;
``
This is the file structure of my React Application. It is under a src file.
Output of App.js
Output of App2.js
#KarthikKK Phil's comment is what you're looking for. Look into the concept of routing and you will see that you will have one component which will decide which route (component) to render.
First you will need to setup the router:
In your index.js:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
{/* The rest of your app goes here */}
</BrowserRouter>,
root
);
Then your App.js:
function App() {
return (
<Routes>
<Route path="/" element={<App1 />} />
<Route path="/app2" element={<App2 />} />
</Routes>
);
}
const App1 = () => {
return (
<div className="LoginPage">
<div className="topnav">
<h1 className="Heading">E-Commerce App</h1>
</div>
<div className="card">
<div className="container">
<h1 className="SignUp">Sign Up</h1>
<form>
<label htmlFor="email" className="email">
<b>Email</b>
</label>
<br/>
<input type="email" name="email" placeholder="Enter your email"/>
<br/>
<label htmlFor="psw" className="Password">
<b>Password</b>
</label>
<br/>
<input
type="password"
name="Password"
placeholder="Enter your password"
/>
<br/>
<label htmlFor="psw-repeat">
<b>Repeat Password</b>
</label>
<br/>
<input
type="password"
name="Repeat Password"
placeholder="Repeat Password"
/>
<br/>
<input type="checkbox" name="Remember Me" className="remember"/>
<label htmlFor="vehicle1"> Remember Me</label>
<br/>
<div className="clearfix">
<button
type="button"
className="cancelbtn"
onClick={() => {
navigate('/app2');
}}
>
Login
</button>
<button type="submit" className="signupbtn">
Sign Up
</button>
</div>
</form>
</div>
</div>
</div>
)
}
const App2 = () => {
return (
<div>
<h1>Hello</h1>
</div>
);
}
export default App;
Full documentation (worth spending a couple hours really understanding this):
https://reactrouter.com/en/main/start/overview
This is index.js, replace this with yours, if you haven't made any change in index.js.
import React from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import "./index.css";
import App from "./App";
import App2 from "./App2";
import reportWebVitals from "./reportWebVitals";
const router = createBrowserRouter([
{
path: "/",
element: <App />,
},
{
path: "/App2",
element: <App2 />,
},
]);
createRoot(document.getElementById("root")).render(
<RouterProvider router={router} />
);
reportWebVitals();
You have to define the route before you use it. You can define it with what component you need render on that route.
Documentation: https://reactrouter.com/en/main/start/overview
Related
I am creating an application where I am getting a parameter from a function and if the parameter equals true I would render a new route instead.
I know how to use react-router-dom as to render new routes you would use something like this
<Link to="/login">Login</Link>
But I don't know how to call it in a function.
function functionName(success){
if (success){
//What do I write here?
// Something like go to path="/login"
}
}
Thank you
(edit)
import { useContext, useState, useEffect } from "react";
import { AuthContext } from "../../Context Api/authenticationAPI";
import { FaUserPlus } from "react-icons/fa";
import { Link, useHistory } from "react-router-dom";
import Alerts from "./Alerts";
const Register = () => {
const history = useHistory();
const { addUser } = useContext(AuthContext);
const data = useContext(AuthContext).data;
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
useEffect(() => {
console.log(data);
if (data.success) {
history.push("/login");
}
}, [data]);
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaUserPlus />
</i>{" "}
Register
</h1>
<Alerts />
<form>
<div className="mb-2">
<label>Name</label>
<input
type="name"
id="name"
name="name"
className="form-control"
placeholder="Enter Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Create Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button
onClick={(e) => {
e.preventDefault();
addUser({ name, email, password });
}}
className="btn btn-primary col-12"
>
Register
</button>
<p className="lead mt-4">
Have An Account? <Link to="/login">Login</Link>
</p>
</form>
</div>
</div>
</div>
);
};
export default Register;
import React from "react";
import { Link } from "react-router-dom";
import { FaSignInAlt } from "react-icons/fa";
const Login = () => {
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaSignInAlt />
</i>{" "}
Login
</h1>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Enter Password"
/>
</div>
<button className="btn btn-primary col-12">Login</button>
<p className="lead mt-4">
No Account? <Link to="/register">Register</Link>
</p>
</div>
</div>
</div>
);
};
export default Login;
You can make use of the history object and programmatically navigate using history.push()
import { useHistory } from 'react-router-dom'
const history = useHistory();
function functionName(success){
if (success) {
history.push('/login')
}
}
Reference
useHistory Hook
I am trying to print "Hello" onto the screen when the add button is clicked. But it is not showing. Thank you in advance for any answers you may have!
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 id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
</div>
);
}
addTask = () => {
return (
<div>
<h2>Hello</h2>
</div>
)
}
}
export default MainPage;
Returning an HTML in an onClickEvent make no sense, where are the result going to be displayed?
I would manage it with a state, something like this
class MainPage extends Component {
this.state = {
buttonPress:false
}
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 id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{{this.state.buttonPress? <h2>Hello</h2> : <span/>}}
</div>
</div>
</div>
</div>
);
}
addTask = () => {
this.setState({buttonPress:true});
}
}
export default MainPage;
Where would the function return the "Hello" code?
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
state = {
showMessage: false
}
addTask= () => {
this.setState({showMessage: true});
};
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 id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{this.state.showMessage && <div>
<h2>Hello</h2>
</div>}
</div>
</div>
</div>
</div>
);
}
}
export default MainPage;
Try this code instead, I created a state which tracks the visibility of the div.
More information here:
How do I display text on button click in React.js
You should use state
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = {testVarible: null}
}
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 id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
{this.state.testVarible}
</div>
);
}
addTask = () => {
this.setState({testVarible: (
<div>
<h2>Hello</h2>
</div>
)});
}
}
export default App;
I wanted to render the sign up page when its clicked in the login page. I am having some issues with the routing. The sign up page is rendering on the same page. I have only created one route on the Login page ("/signup"). My goal is to just render a new page with just the sign up details. I thought by adding exact it would fix it.
import React from 'react';
import './Login.css';
import {Route, Link, BrowserRouter as Router} from 'react-router-dom'
import Signup from "./Signup";
import Home from "./Home";
function Login() {
return (
<div class="login-page">
<h2 id="projectName" class="text-center"> login. </h2>
<div class="form">
<form class="login-form">
<input type="text" placeholder="Username"/>
<input type="password" placeholder="Password"/>
<button>login</button>
<Router>
<p class="message">New user ->
<Link to="/signup">Sign up</Link>
</p>
<Route path="/signup" exact={true} component={Signup} />
</Router>
<p class = "message"> Forgot Password or Forgot Username </p>
</form>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="tagline text-center"></h1>
</div>
</div>
</div>
</div>
);
}
export default Login;
import React from 'react';
import './Login.css';
function Signup() {
return (
<div class="login-page">
<h2 id="projectName" class="text-center"> signup.</h2>
<div class="form">
<form class="login-form">
<input type="text" placeholder="First name"/>
<input type="text" placeholder="Last name"/>
<input type="email" placeholder="Email"/>
<input type="text" placeholder="Username"/>
<input type="password" placeholder="Password"/>
<button>Sign up</button>
<p class="message">Already have an account -> Login</p>
</form>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="tagline text-center"></h1>
</div>
</div>
</div>
</div>
);
}
export default Signup;
image of how the page looks with the login, and signup -> I have only set one route
render login component through
<Route path="/" exact component={login} />
in app.js file
hope this will solve your issue
try this in login.js component
import React from 'react';
import {Link} from 'react-router-dom'
function Login() {
return (
<div class="login-page">
<h2 id="projectName" class="text-center"> login. </h2>
<div class="form">
<form class="login-form">
<input type="text" placeholder="Username"/>
<input type="password" placeholder="Password"/>
<button>login</button>
<p class="message">New user ->
<Link to="/signup">Sign up</Link>
</p>
<p class = "message"> Forgot Password or Forgot Username </p>
</form>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="tagline text-center"></h1>
</div>
</div>
</div>
</div>
);
}
export default Login;
in signup.js
import React from 'react';
function Signup() {
return (
<div class="login-page">
<h2 id="projectName" class="text-center"> signup.</h2>
<div class="form">
<form class="login-form">
<input type="text" placeholder="First name"/>
<input type="text" placeholder="Last name"/>
<input type="email" placeholder="Email"/>
<input type="text" placeholder="Username"/>
<input type="password" placeholder="Password"/>
<button>Sign up</button>
<p class="message">Already have an account -> Login</p>
</form>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="tagline text-center"></h1>
</div>
</div>
</div>
</div>
);
}
export default Signup;
create routing component to redirect to other component
import React from 'react';
import {Route, Switch} from 'react-router-dom';
import Signup from './Signup'
const Routes = () => {
return(
<Switch>
<Route path="/signup" exact={true} component={Signup} />
</Switch>
)
}
export default Routes;
This question already has answers here:
Programmatically Navigate using react-router
(9 answers)
Closed 4 years ago.
I am relatively a beginner in ReactJS. I have been looking for the answer to this question for quite some time now. I have a form which is to be split into 2 parts. The first part contains a few text inputs and radio buttons. There is a Proceed button at the end of Part 1. The button is as below :
<div className="ProceedButton">
<button name="Proceed" type="button" onClick={this.handleClick}>Proceed</button>
</div>
This is the click handler for the Proceed Button :
handleClick(event){
console.log(this.state);
firebase.database()
.ref('registrations/'+this.state.userID)
.set(this.state);
firebase.database()
.ref('registrations/userID')
.set(this.state.userID);
}
So after clicking the Proceed button, I have to store the data on the database and move on to Part 2 of the form which is to be displayed on a new page. Is there a way I can redirect to Part 2 from within handleClick()? If not how else do I achieve it with minimum amount of code?
Thanks in advance.
Here's the complete code for part 1 of the form :
import React, { Component } from 'react';
import firebase from './firebase.js';
import { Router, Route, Link, IndexRoute, IndexLink, Switch, HashHistory, BrowserHistory, withRouter } from 'react-router-dom';
class IntroForm extends Component{
constructor(){
super();
this.state={
userID:1,
state:"",
age:'',
ethnicity:"Hispanic or Latino",
race:"American Indian",
sex:"Male",
height:"",
weight:"",
};
console.log(this.state);
this.handleInputChange=this.handleInputChange.bind(this);
this.handleClick=this.handleClick.bind(this);
}
componentDidMount(){
const dbRef=firebase.database().ref().child('registrations');
const countRef=dbRef.child('userID');
countRef.on('value',snap=>{
this.setState({
userID:(snap.val()+1)
});
});
}
handleInputChange(event){
const target=event.target;
const name=target.name;
var value;
if((target.type==="radio"&&target.checked)||target.type!=="radio") value=target.value;
this.setState({
[name]:value
});
}
handleClick(event){
console.log(this.state);
firebase.database().ref('registrations/'+this.state.userID).set(this.state);
firebase.database().ref('registrations/userID').set(this.state.userID);
}
render() {
return(
<div>
<div className="State">
<div className="Head">
State
</div>
<div className="StateField">
<input
name="state"
type="text"
onChange={this.handleInputChange} />
</div>
<hr />
</div>
<div className="Age">
<div className="Head">
Age
</div>
<div className="AgeField">
<input
name="age"
type="number"
onChange={this.handleInputChange} />
</div>
<hr />
</div>
<div className="Ethnicity">
<div className="Head">
Ethnicity
</div>
<div className="EthnicityField">
<input name="ethnicity" type="radio" value="Hispanic or Latino" onClick={this.handleInputChange} defaultChecked /> Hispanic or Latino
<input name="ethnicity" type="radio" value="Non-Hispanic or Non-Latino" onClick={this.handleInputChange} /> Non-Hispanic or Non-Latino
</div>
<hr />
</div>
<div className="Race">
<div className="Head">
Race
</div>
<div className="RaceField">
<input name="race" type="radio" value="American Indian" onClick={this.handleInputChange} defaultChecked /> American Indian
<input name="race" type="radio" value="Asian" onClick={this.handleInputChange}/> Asian
<input name="race" type="radio" value="Native Hawaiian or Other Pacific Islander" onClick={this.handleInputChange}/> Hawaiian or Other Pacific Islander
<input name="race" type="radio" value="Black or African American" onClick={this.handleInputChange}/> Black or African American
<input name="race" type="radio" value="White" onClick={this.handleInputChange}/> White
</div>
<hr />
</div>
<div className="Sex">
<div className="Head">
Sex
</div>
<div className="SexField">
<input name="sex" type="radio" value="Male" onClick={this.handleInputChange} defaultChecked /> Male
<input name="sex" type="radio" value="Female" onClick={this.handleInputChange}/> Female
</div>
<hr />
</div>
<div className="Height">
<div className="Head">
Height
</div>
<div className="HeightField">
<input name="height" type="number" placeholder="In inches" onChange={this.handleInputChange}/>
</div>
<hr />
</div>
<div className="Weight">
<div className="Head">
Weight
</div>
<div className="WeightField">
<input name="weight" type="number" placeholder="In pounds" onChange={this.handleInputChange}/>
</div>
<hr />
</div>
<div className="ProceedButton">
<button name="Proceed" type="button" onClick={this.handleClick} >Proceed</button>
</div>
</div>
);
}
}
export default IntroForm;
App.js :
import React, { Component } from 'react';
import './App.css';
import TopBar from './js/TopBar.js';
import { Router, Route, Link, IndexRoute, IndexLink, Switch, HashHistory, BrowserHistory, withRouter } from 'react-router-dom';
import IntroForm from './js/IntroForm.js';
class App extends Component {
render() {
return (
<div className="App">
<Switch>
<Route exact path="/" component={StartButton}/>
<Route exact path="/intro" component={IntroForm}/>
</Switch>
</div>
);
}
}
const StartButton = withRouter(({ history }) => (
<button
type='button'
name="StartButton"
style={{"background":"#0000ff","textAlign":"center","color":"#ffffff","width":"100px","height":"30px"}}
onClick={() => { history.push('/intro') }}
>
Start
</button>
))
export default App;
You need to add a <Route /> in your <Switch /> for the second part of the form, and then in the first form you can do:
this.props.history.push('/form2').
I am trying to implement react into a small piece of a website, but for some reason it is not rendering what so ever. I am using node, express, React, and handlebars.
landing.handlebars:
<section class="section section-dark">
<div id="root"></div>
<script type="text/jsx" src="index.js"></script>
index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
App.jsx:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: null,
email: null,
message: null,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<div className="App">
<h2 className="bottom">Send Message!</h2>
<form onSubmit={this.handleSubmit} className="bottom">
<div className="form-group">
<label for="exampleInputEmail1">Email address:</label>
<input type="email" onChange= {this.handleChange} value = {this.state.email} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div classNameName="form-group">
<label for="exampleInputPassword1">Name:</label>
<input type="text" onChange= {this.handleChange} value={this.state.name} className="form-control" id="exampleInputPassword1" placeholder="Name" />
</div>
<div className="form-group">
<label for="exampleTextarea">Message:</label>
<textarea onChange= {this.handleChange} value={this.state.message} className="form-control" id="exampleTextarea" rows="3"></textarea>
</div>
<button type="submit" value="submit" className="btn btn-primary"> <i
className="fa fa-paper-plane" aria-hidden="true"></i> Send</button>
</form>
</div>
);
}
}
export default App;
It shows no sort of jsx file in the network tag at all besides the ones that are necessary (Jquery, bootstrap, etc)