Reputation: 149
I am very new to react and I'm stuck on how to render a new componant when a user logs in.
I first want to display a log in page (which just requires text and pressing submit) once submit has been pressed I would like it to load a new page so the user no longer sees the login box.
I currently have a form and when the user presses submit the new page I would like to display renders below the current login rather than replacing it, how would I go about changing this please?
import React,{Component} from 'react';
import LoggedIn from './LoggedIn ';
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {value: '',
showComponent: false,
};
this.handleChange = this.handleChange.bind(this);
this._handleSubmit = this._handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
_handleSubmit(event) {
event.preventDefault();
this.setState({
showComponent: true,
});
}
render() {
return (
<div>
<div>
<p>Enter your username to continue</p>
</div>
<div>
<form onSubmit={this._handleSubmit}>
<label>
Username:
<input type="text" name="UserId" value={this.state.value} onChange=
{this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
{this.state.showComponent ?
<LoggedIn /> :
null
}
</div>
</div>
);
}
}
export default LogIn;
Logged in component is current just a blank page with the text 'test'
import React from 'react';
function LoggedIn() {
return (
<div>
<p>Test</p>
</div>
);
}
export default LoggedIn;
Upvotes: 2
Views: 1347
Reputation: 1638
You can use React Router to setup routes and go to your test page when submit button is clicked from log in page,
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from "./Home";
import Login from "./Login";
export default function App() {
return (
<Router>
<Switch>
<Route path="/home" component={Home}></Route>
<Route path="/login" component={Login}></Route>
<Route path="/" exact component={Login}></Route>
</Switch>
</Router>
);
}
you can see my sample here
Upvotes: 2