I am simply trying to click on a component and have react rerender what is needed to be rendered. But I simply can't archive that. This is what I have so far:
Index.js (This is where I tried to store all my routes)
import React from "react";
import ReactDOM from "react-dom";
import Main from "./pages/index/main.js";
import Login from "./pages/signin/signin.js";
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
ReactDOM.render(
<div>
<Router>
<Switch>
<Route exact path="/" render={()=> <Main />}/>
<Route path="/login" render={()=> <Login />}/>
</Switch>
</Router>
</div>,
document.getElementById("root")
);
Header.JS ( Where I have the Link tags setup )
import React from "react";
import style from "./../acc/css/navbar.css";
import { BrowserRouter as Router, Link} from "react-router-dom";
export default class Header extends React.Component {
render() {
return (
<Router>
<section className={style.nav} id="nav">
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
</section>
</Router>
);
}
}
As of now, when I manually go to /
, it renders the Main
component, and when I manually go to /login
, it renders the Login
component.
However, when I click on the <Link>
component, it doesn't render, it just changes the URL to /login
or vise versa.
I was wondering if there is any solution to this issue?
Main.js code
import React from "react";
//import compunts
import Header from "./../header.js";
import Qoute from "./qoute.js";
import Grades from "./grades.js";
export default class Main extends React.Component {
render() {
return (
<div id="continor">
<Header />
<Qoute />
<Grades />
</div>
);
}
}
Signin.js
import React from "react";
import Header from "./../header.js";
import Qoute from "./qoute.js";
import Form from "./form.js";
export default class Login extends React.Component {
render() {
return(
<div>
<Header />
<section id="info">
<div className="containor">
<div className="row">
<Qoute />
<Form />
</div>
</div>
</section>
</div>
);
}
}
For clarification, I have tried the
<Route exact path="/" component={Main}/>
and that still doesn't work. Any solutions?
Now you have <Link>
elements inside the <Router>
tag. You have to remove this <Router>
and links starts works.
Try changing your Header.js as,
import React from "react";
import style from "./../acc/css/navbar.css";
import { BrowserRouter as Router, Link} from "react-router-dom";
export default class Header extends React.Component {
render() {
return (
<section className={style.nav} id="nav">
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
</section>
);
}
}
And click on a link it shows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.