React router page doesn't reload - reactjs

I have a problem with react-router. The page content doesn't update when I click on a link (I'm using Link from react-router), although the URL is updated. Below is the source code:
React.render(
<Router>
<Route path="/" component={App}>
<IndexRoute component={Dashboard} />
<Route path="phase/:phaseNo" component={PhaseDetail}/>
</Route>
</Router>, document.getElementById("glyco-edu")
);
PhaseDetail.js:
var React = require("react");
var PhaseDetail = React.createClass({
render: function () {
return( <div>
Example Text
</div>
);
}
});
module.exports = PhaseDetail;
Link element:
<Link to={'/phase/'+this.props.phaseNo}>
{images}
</Link>
I'm using react-router-1.0.0-rc3 and react-0.13.3.
Thank you.

Related

Routing pages into components: React

I have 3 components: Header.js, Main.js, and Footer.js, and App.js is like
const App = () => {
<Header/>
<Main/>
<Footer/>
}
In the Header.js I have links like About and Projects. I would like to be able when I click About in the header for example to display the page About.js in Main.js, and when I click Projects to display the page Projects.js in the Main.js component. I tried to use Routing in the Main.js component like
const Main = () => {
<Router>
<Switch>
<Route exact path='/' component={About.js} />
<Route exact path='/projects' component={Projects.js} />
</Switch>
</Router>
}
but it wouldn't allow me, saying that I cannot use Link outside a router, where I use Link in the Header.js. How can I achieve this?
The Header.js is the following
const Header = () => {
return (
<div>
<ul>
<li>
<Link to="/">
About
</Link>
</li>
<li>
<Link to="/projects">
Projects
</Link>
</li>
</ul>
</div>
)
}
You simply need to make sure your Router component surrounds any components doing routing. For simplicity, here’s the router surrounding your whole app at the App level.
const App = () => {
<Router>
<Header/>
<Main/>
<Footer/>
</Router>
}
Edit: make sure you’re passing your components correctly to the Routes:
const Main = () => {
<Switch>
<Route exact path='/' component={About} />
<Route exact path='/projects' component={Projects} />
</Switch>
}

How to reload component when URL is changed in react router

In my React Application I need to reload the component when it comes to the path path="/". I know react-router helps us reload easily the current component but I really need this in my application for some styling purpose. In my application I have two paths:
<Route path="/" component={newRoute}/>
and <Route path="/gallery" component={GalleryImages}/>. So, whenever I move from GalleryImages to newRoute I need to reload the newRoute components otherwise the styles are not working. What is the way around here? Here's myApp.js now:
const newRoute = () => {
return (
<div id="colorlib-page">
<div id="container-wrap">
<div id="colorlib-main">
<Introduction/>
<About/>
<Projects/>
<Timeline/>
<Blog/>
</div>
</div>
</div>
)
}
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Sidebar/>
<Switch>
<Route path="/" component={newRoute} exact/>
<Route path="/gallery" component={GalleryImages} exact/>
<Route component={Error}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
Try to use class component instead of functional component

How to navigate on a page without reloading the page

I have navigation in react and want to redirect to the listing page on click.using this right now which is loading the page
This is my Header.js file
return (
<Link to="/allusers">All Users</Link>
);
This is my App.js file
I imported this
import UsersList from './user/UsersList'; //then i defined
class App extends Component {
render () {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/userlist' component={UsersList} />
</Switch>
</div>
</BrowserRouter>
)
}
}
You can check react-router or #reach/router
For example, in #reach/router, you can use the provided Link component to create the same anchor as in your example:
<Link to="/userlist">All Users</Link>
And create a router with all your routes:
<Router primary={false}>
<Home path="/" />
<AllUsers path="/allusers" />
<NotFound default />
</Router>
https://github.com/reach/router
You can play around with this example: https://reach.tech/router/tutorial/04-router
Same thing can be done with react-router.
This achieved through a client side routing: manipulation of the history object of the browser through client side
This is an example rendering a specific component for specific route
import { BrowserRouter, Route, Link, Switch } from "react-router-dom"
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/allusers" component={AllUsers} />
<Route component={NotFoundPage} />
</Switch>
</BrowserRouter>
// then just pair it up with a navigation bar
<Link to="/">All Users</Link>
<Link to="/allusers">All Users</Link>
These components tied up to a route has access to history object as prop where you can call history.push('/allusers') for other use cases
reference:
https://reacttraining.com/react-router/web/guides/quick-start
You can do that as follows:
goToUserList = () => {
this.props.history.push('/userlist')
}
...
return(
<button onClick={this.goToUserList}>Go User List</button>
)
Hope it helps.

Navigation from component to another componet

I have login component and dashboard. My application entry point is login page. After successful login, I want move to main page(dashboard & navigation).
I tried this like the following but its not working. After login not able to move to dashboard.
My login Component is
var React = require('react');
var {Link} = require('react-router');
var Dashboard = require('Dashboard');
var Login = React.createClass ({
onFormSubmit: function(e){
e.preventDefault();
<Dashboard />
},
render: function(){
return (
<div>
<h1 className="text-center">Login</h1>
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="username"/>
<button className="button">Login</button>
</form>
</div>
)
}
});
module.exports = Login;
My Dashboard component is
var React = require('react');
var Nav = require('Nav');
var Dashboard = (props) => {
return (
<div>
<Nav/>
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
}
module.exports = Dashboard;
Main app.jsx file is
var React = require('react');
var ReactDOM = require('react-dom');
var {Route, Router, IndexRoute, hashHistory} = require('react-router');
var Login = require('Login');
var Dashboard = require('Dashboard');
var About = require('About');
var Examples = require('Examples');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Login}>
<Route component={Dashboard}>
<Route path="about" component={About}/>
<Route path="examples" component={Examples}/>
</Route>
</Route>
</Router>,
document.getElementById('app')
);
Your onFormSumit() should be like this
onFormSubmit: function(e){
e.preventDefault();
window.location.href = '/dashboard'
},
And your <Router/> in app.jsx should be like this
<Router history={hashHistory}>
<Route path="/" component={Login} />
<Route path="dashboard" component={Dashboard} />
<Route path="about" component={About}/>
<Route path="examples" component={Examples}/>
</Router>
This will make the browser redirect to /dashboard on form submit. That redirected url(/dashboard) will be captured by the <Router/> and the component for that path will be rendered.
[Update]
In your express, you nee to add the path so that it always returns the index.html page. Add this
app.get(['/', '/dashboard'], function(req, res){
res.sendfile('./path to your index.html file')
})
or you can do the following also
app.get('*', function(req, res){
res.sendfile('./path to your index.html file')
})
For further read, check this

React-router link doesn't work

React-router is off to a really bad start... What seems basic doesn't work. Using react-router 2.0.0 my Link component updates the URL to be /about, but my page doesn't render the About component after that...
Entry point js
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var hashHistory = require('react-router').hashHistory;
var App = require('./components/App.react');
var About = require('./components/About');
ReactDOM.render(
<Router history={hashHistory} >
<Route path="/" component={App}>
<Route path="about" component={About} />
</Route>
</Router>,
document.getElementById('app')
);
App.js
'use strict';
var React = require('react');
var Link = require('react-router').Link;
var Header = require('./Header');
var UserPanel = require('./UserPanel');
var ModelPanel = require('./ModelPanel.react');
var EventPanel = require('./event/EventPanel');
var VisPanel = require('./vis/VisPanel');
var LoginForm = require('./LoginForm');
var AppStore = require('../stores/AppStore');
var AppStates = require('../constants/AppStates');
var App = React.createClass({
[... code omitted ...]
render: function() {
var viewStateUi = getViewStateUi(this.state.appState);
return (
<div>
<Header />
<Link to="/about">About</Link>
{viewStateUi}
</div>
);
}
});
For some reason, the <Link>s were not working for me with the configuration below.
// index.js
ReactDOM.render(
<Provider store={store}>
<BrowserRouter >
<App />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
// App.js
return (
<div className="App">
<Route exact={true} path="/:lang" component={Home} />
<Route exact={true} path="/" render={() => <Redirect to={{ pathname: 'pt' }} />} />
<Route path="/:lang/play" component={Play} />} />
<Route path="/:lang/end" component={End} />
</div >
);
The Home component had the Link, but Links on the App would do the same. Every time I clicked it, it would only change the url, but the views would stay the same.
I was able to put it working when I added withRouter to the App.js
export default withRouter(connect(mapStateToProps, { f, g })(App));
I still don't understand what happened. Maybe it's related with redux or there is some detail I'm missing.
Since the 'About' route is a child of the 'App' route, you need to either add this.props.children to your App component:
var App = React.createClass({
render: function() {
var viewStateUi = getViewStateUi(this.state.appState);
return (
<div>
<Header />
<Link href="/about">About</Link>
{viewStateUi}
{this.props.children}
</div>
);
}
});
or separate your routes:
ReactDOM.render(
<Router history={hashHistory} >
<Route path="/" component={App} />
<Route path="/about" component={About} />
</Router>,
document.getElementById('app')
);
None of the solutions worked for me, including adding withRouter to my Component. I was experiencing the same issue where the browser's address bar updates the URL but the component doesn't render. During the debugging of my issue, I realize I have to present the context of my problem because it is a bit different from what the OP had.
The route I was trying to get to work was a dynamic route that takes an arbitrary parameter, e.g.
<Route path={`/hr/employees/:id`} component={EmployeePage} />
The component this route uses is "self-referential", meaning that within the component or its children components, they have a Link component that directs to /hr/employees/:id, but with a different id. So let's say if I was at /hr/employees/3 and on the page, there was a link to /hr/employees/4, e.g. <Link to='/hr/employees/4'>, I would get this problem where the component didn't re-render.
To solve this problem, I simply modified the componentDidUpdate method of my EmployeePage component:
componentDidUpdate(prevProps) {
if (this.props.match.params.id !== prevProps.match.params.id) {
// fetch data
}
}
If you're using functional components, use useEffect:
const EmployeePage = props => {
const {id} = props.match.params
useEffect(() => {
// fetch data
}, [id])
}

Resources