I'm struggling to render a component based on routes from the React-Router. When the route is dynamic I can't seem to figure out a way to match the route.
I have created a component "Navbar" which I want to render only on specific routes. For this purpose I created a separate component "Tracker" which matches the route and renders the "Navbar" component.
Tracker.js snippet:
class Tracker extends Component {
render() {
var NavVisible =
this.props.location.pathname === "/feed" ||
this.props.location.pathname === "/explore" ||
this.props.location.pathname === "/chatroom" ||
this.props.location.pathname === "/username" ? (
<Navbar />
) : null;
return <div>{NavVisible}</div>;
}
}
Suppose if I have to display the Navbar component in "feed/(some_dynamic_path)", how should I write the condition?
A solution would be greatly appreciated.
Thanks.
Edit: App.js
import React, {Component} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
class App extends Component{
render(){
const DefaultContainer = () => (
<div>
<Route path='/home' component={ft}/>
<Route path='/explore' component={exp}/>
<Route path='/compose' component={add}/>
<Route path='/chatroom' component={msg}/>
<Route path='/user' component={usrpro}/>
</div>
)
return (
<BrowserRouter>
<div className="App">
<Tracker/>
<Switch>
<Route path='/' exact component={Splash}/>
<Route exact path="/(compose)" component={noNavContainer}/>
<Route exact path="/(newtext)" component={noNavContainer}/>
<Route path="/(login)" component={login}/>
<Route component={DefaultContainer}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
You can try something like:
this.props.location.pathname === '/feed/' + this.props.params.id
Might get you started: https://jaketrent.com/post/access-route-params-react-router-v4/
You can include Routers for various urls like this in your app.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
class App extends React.Component {
render () {
return (
<Router>
<Home>
<Switch>
<Route path='/feed/:path_variable' component={Navbar} />
</Switch>
</Home>
</Router>
)
}
}
Also In Navbar Component, You will get access to this.props.match.params.path_variable whose value changes based on the URL.
Read more about it in this nicely written article.
https://scotch.io/courses/using-react-router-4/route-params
Related
Hello in my directions file I set my struct
header
navbar
and my switch
foote
const AppRouter = () => (
<BrowserRouter>
<Route path="/login" component={AuthPage} exact={true} />
<Route path="/dashboard/addProduct" component={AddProduct} exact={true} />
<div>
<Header/>
<Navigation/>
<Container maxWidth="lg" >
<Switch>
<Route path="/" component={LandingPage} exact={true} />
<Route path="/xd" component={AuthPage} exact={true} />
<Route component={NotFoundPage} />
</Switch>
</Container>
</div>
</BrowserRouter>
);
But I have two routes where I didn't want to show my header
footer
and nav bar
which are the login and addproduct routes
how could i do that?
This is a little bit hacky (just to match your current approach) since I'm assuming you just want to hide those components in only those 2 routes, You can use withRouter in your Header and Navigation components, withRouter will provide to you the location prop and you can have a condition like this:
import React from "react";
import { withRouter } from "react-router-dom";
const Navigation = props => {
const { location } = props;
const { pathname } = location;
if (pathname !== "/login" || pathname !== "/dashboard/addProduct" ) {
return (
// Component logic goes here
);
}
// if we're on those routes we should return null to not render anything
return null;
};
export default withRouter(Navigation);
If you want a more robust long term approach this answer could help:
How to hide navbar in login page in react router
I'm starting in React and I'm curious about about if have any way to change a page without reload all the html, changing only a content component for example.
I know that there is a way to change the component without change the url but I thought that if the url change too the application would be better.
React Router is the exact thing you're looking for
Here, how you can achieve what you're looking for.
First, wrap your app with BrowserRouter
import { BrowserRouter } from "react-router-dom";
import React from 'react';
class App extends React.Component {
return (){
return (
<BrowserRouter>
<SomeComponent />
</BrowserRouter>
)
}
}
Now just use the Route and Link. Route told the application which component to render on the basis of the current route and Link changes the URL without reloading the whole page
import { Route, Link, Switch } from "react-router-dom";
import React from 'react';
import {Circle, Square} from './someFileWithComponents';
class SomeComponent extends React.Component {
render(){
return (
<div>
<Link to='/circle' >Circle</Link>
<Link to='/square' >Square</Link>
<Switch>
<Route path='/circle' component={Circle} />
<Route path='/square' component={Square} />
</Switch>
</div>
)
}
}
React Router is what you looking for
const AppRouter =()=>(
<BrowserRouter>
<div>
<Header/>//where Header components contains the navigation
<Switch>
<Route path="/" component={BookListPage} exact={true} />
<Route path="/create" component={AddBookItem} />
<Route path="/edit/:id" component={EditBookItem} />
<Route path="/help" component={HelpPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
I'm building a multilingual site in React and I'm using react router for my routing. Right now I have it setup where the prefix has to be present in order to transition to the route.
What I'm trying to do is the following: When I go to localhost:3000 I want my app to transition to the home component. And when I go to
localhost:3000/jp I still want to transition to the home component except now my language prefix would be jp.
I want English to be the default language and for other languages they have to be present in the prefix.
Right now it only transitions to the home component if I enter localhost:3000/en.
Is there a way to accomplish this?
import React, { Component } from 'react';
import { Route, Switch } from "react-router-dom";
import { Home } from '../containers/home';
import { About } from '../containers/about';
import { Contact } from '../containers/contact';
export default class Routes extends Component {
render(){
return(
<Switch>
<Route path="/:lang/about" component={About} />
<Route path="/:lang/contact" component={Contact} />
<Route path="/:lang/" component={Home} />
</Switch>
);
}
}
Just add a Redirect at the end which will be matched when nothing else does and it will redirect to the /en
import React, { Component } from 'react';
import { Route, Switch, Redirect } from "react-router-dom";
import { Home } from '../containers/home';
import { About } from '../containers/about';
import { Contact } from '../containers/contact';
export default class Routes extends Component {
render(){
return(
<Switch>
<Route path="/:lang/about" component={About} />
<Route path="/:lang/contact" component={Contact} />
<Route path="/:lang/" component={Home} />
<Redirect to="/en" />
</Switch>
);
}
}
Demo at https://codesandbox.io/s/18rm8k82lj
Updated answer (due to comment)
The problem is that the /:lang/ will match /about and the lang will be set to about.
A solution is to use the render prop of the route and decide what you want to do there
export default class Routes extends Component {
render() {
const supportedLanguages = ["en", "jp", "de", "es"];
return (
<Switch>
<Route path="/:lang/about" component={About} />
<Route path="/:lang/contact" component={Contact} />
<Route
path="/:lang/"
render={props =>
supportedLanguages.includes(props.match.params.lang) ? (
<Home {...props} />
) : (
<Redirect to={`/en/${props.match.params.lang}`} />
)
}
/>
</Switch>
);
}
}
Demo at https://codesandbox.io/s/k2n9997345
I have a simple App that uses BrowserRouter from 'react-router-dom' v4. I'm trying to access the location.pathname property from within the <BrowserRouter/> component, without avail:
class App extends Component{
render(){
return (
<BrowserRouter>
// How do I access this.props.location?
<div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
<Switch>
<Route path="/login" component={LoginPage}/>
<Route path="/success" component={LoginSuccess}/>
<Route path="/account" component={MyAccount}/>
...
<Route component={Error404}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
I know that I can access the app's current path location through the child components with this.props.location.pathname, but I need to access it from the parent component, just below <BrowserRouter/> to run additional logic that doesn't pertain to child components. How can I get this location?
You can also do it using withRouter which has a similar result to putting the code in a render parameter and avoids the need for a "fake" <Route/>.
Essentially you put the JSX that needs to know the location in a component of its own, which is wrapped by withRouter. This supplies the location to the component:
import { withRouter } from 'react-router-dom';
const Content = withRouter(props =>
<div className={(props.location.pathname === "/account") ? "backg...
...
</div>
);
Then you use that in your main router section:
class App extends Component{
render() {
return (
<BrowserRouter>
<Content/>
...
Since react-router v5.1.0 you can use useLocation.
https://reactrouter.com/web/api/Hooks/uselocation
class App extends Component{
render(){
const location = useLocation();
return (
<div className={(location.pathname === "/account") ? "bgnd-black" : "bgnd-white"} >
//...
</div>
);
}
}
// ...
<BrowserRouter>
<App />
</BrowserRouter>
After digging through their GitHub issues, I found the solution. I must render a <Route /> within <BrowserRouter /> and pass the rest of my app into its render() function with history as a parameter. Within the render function, I can find the app's location in history.location.pathname.
class App extends Component{
render(){
return (
<BrowserRouter>
// We must add a parent <Route> and render its children while passing 'history' as parameter
<Route path={Paths.reserve} render={(history) =>
// Within render(), we can find it in history.location.pathname
<div className={(history.location.pathname === "/account") ? "background-black" : "background-white"} >
<Switch>
<Route path="/login" component={LoginPage}/>
<Route path="/success" component={LoginSuccess}/>
<Route path="/account" component={MyAccount}/>
...
<Route component={Error404}/>
</Switch>
</div>
}/>
}} />
</BrowserRouter>
);
}
}
This will update the history parameter automatically, without having to re-render on componentDidMount() or componentDidUpdate()
You achieve what u have asked for by doing this
import AccessRoute from './AccessRoute'
class App extends Component{
render(){
return (
<BrowserRouter>
<AccessRoute>
<div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
<Switch>
<Route path="/login" component={LoginPage}/>
<Route path="/success" component={LoginSuccess}/>
<Route path="/account" component={MyAccount}/>
...
<Route component={Error404}/>
</Switch>
</div>
</AccessRoute>
</BrowserRouter>
);
}
}
AccessRoute.jsx
import React from 'react'
import {withRouter} from 'react-router';
class AccessRoute extends React.Component{
constructor(props){
super(props);
}
//If you want to find the location on mount use this
componentDidMount(){
console.log("the path name is ",this.props.location.pathname);
}
//If you want to find the location on change use this
componentDidUpdate(prevprops){
if(this.props.location.pathname!=prevprops.location.pathname){
console.log("the new path name is ",this.props.location.pathname);
}
}
render(){
return(
this.props.children
);
}
}
export default withRouter(AccessRoute)
I have some nested routes written in react router v4 and in the Navigation component I have an input box.
On submit I need to call a method on a different route (on Landing component) and pass the value. I can't find any example to call a method in Route.
Any other way/ workaround to use a navigation with data and different routes is welcome.
My routes:
return (
<div>
<Navigation callSearch = {this.callSearch.bind(this)} />
<Switch>
<Route path="/u/:slug" component={AuthorPage}/>
<Route path="/:location/:slug" component={PhotoDetails}/>
<Route path="/" component={Landing} />
</Switch>
</div>
)
In Navigation i call callSearch() :
searchPhotos(e) {
e.preventDefault();
if(this.state.searchTerm) {
this.props.callSearch(this.state.searchTerm);
}
}
I have fixed this issue in my application using withRouter from react-router module.
import { Route } from "react-router-dom";
import { withRouter } from "react-router";
class SideBar extends Component {
callSearch = (searchKeyword) => {
if(searchKeyword) this.props.history.push(`/u/${searchKeyword}`);
};
render() {
return (
<div>
<Navigation callSearch = {this.callSearch} />
<Switch>
<Route path="/u/:slug" component={AuthorPage}/>
<Route path="/:location/:slug" component={PhotoDetails}/>
<Route path="/" component={Landing} />
</Switch>
</div>
)
}
export default withRouter(SideBar);
Hope this will help anyone else !!!