Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  162] [ 4]  / answers: 1 / hits: 5330  / 4 Years ago, wed, september 16, 2020, 12:00:00

I want to have a simple button that when clicked redirects a user to a route defined in my Index.tsx file.


When the button is clicked, the url bar is correctly changed to "/dashboard", however my component (just an h1) does not appear. If I reload chrome at that point it will appear.


Here's my code (Index.tsx):


import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Route, Switch } from "react-router-dom";
import { Router } from "react-router";
import { createBrowserHistory } from "history";
import Dashboard from "./components/Dashboard";

const appHistory = createBrowserHistory();

ReactDOM.render(
<React.StrictMode>
<Router history={appHistory}>
<Switch>
<Route exact path="/" component={App} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>
</React.StrictMode>,
document.getElementById("root")
);

Here's my start of a Login form (the first route above, App, renders it).
(Login.tsx):


 import React, { useState } from "react";
import {Button} from "@material-ui/core";
import { useHistory} from "react-router-dom";

export const Login: React.FC = (props) => {
const classes = useStyles();
let history = useHistory();

const [email, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");

const validateForm = (): boolean => {
return true;
};

const handleLoginClick = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
history.push("/dashboard");
};

return (
<form>
<div>
<Button
onClick={handleLoginClick}
color="inherit"
type="button"
>
Login
</Button>
</div>
</form>
);
};

export default Login;

More From » reactjs

 Answers
2

Replace this line


import { Router } from "react-router"

with


import {BrowserRouter as Router } from "react-router-dom";

[#2673] Saturday, September 12, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
felixa

Total Points: 180
Total Questions: 113
Total Answers: 108

Location: Palau
Member since Sat, Aug 21, 2021
3 Years ago
;