I tried to move BrowserRouter out of my component. My App looked like this:
class App extends Component {
constructor(props) {
super(props);
this.state = {
}
}
render() {
return (
<BrowserRouter>
<main>
<Menu />
<Switch>
<Route exact path="/about" component = {About} />
<Route exact path="/admin" component = {BooksForm} />
<Route exact path="/cart" component = {Cart} />
<Route exact path="/" component = {BookList} />
</Switch>
<Footer />
</main>
</BrowserRouter>
);
}
}
And everything was working fine. But when I pulled BrowserRouter up, so my index.js would look like this:
const renderApp = () => (
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
)
const root = document.getElementById('app')
render(renderApp(), root)
it stopped working. When I click on one of the links the url changes but there's no change in my app. It renders new componennt only if I reload the page. How can I make it work without placing router component in the same component as Switch?
Tough to tell without looking at the rest of the code. Are you using the proper react-router <Link>s? I assume you don't have the <BrowserRouter> element in both components, can't imagine that nesting them would do any good.
I'm on an old version of react-router, so I'm seeing some of these examples for the first time, but it looks like you don't need the exact keyword on all of those <Route>s within <Switch> -- the switch guarantees that only one of them will math.
Allright I've made it working again. Connect from redux was causing the problem and withRouter solved it
Related
This question already has an answer here:
Why I receive blank page? React
(1 answer)
Closed 6 months ago.
This is my app.js
I'm trying to preview the code but it's showing a blank page like extremely blank not even with an error while on my terminal it says compiled successfully!
import TopBar from './components/topbar/TopBar';
import Home from './pages/home/home';
import Write from './pages/write';
import Single from './pages/single';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
function App() {
return (
<>
<Router>
<TopBar/>
<Routes>
<Route exact path ="/" element = {Home} />
<Route path ="/write" element = {Write} />
<Route path ="/single" element = {Single} />
</Routes>
</Router>
</>
);
}
export default App;
With React Router Dom v6 you should be calling the given component to element property, like so:
<Route exact path ="/" element = {<Home/>} />
<Route path ="/write" element = {<Write/>} />
<Route path ="/single" element = {<Single/>} />
Check your browser console to see more details.
but as far as i know in version 6 there is no exact in <Route/> props remove it
try removing exact and using child routers I think that would help
function App() {
return (
<>
<Router>
<TopBar />
<Routes>
<Route path="/" element={Home}>
<Route path="write" element={Write} />
<Route path="single" element={Single} />
</Route>
</Routes>
</Router>
</>
);
}
In my react app I currently have this:
<Router>
<div class Name="App">
<Route path="/" exact component={PersonList} />
<Route path="/rules" exact component={RulesPage} />
<Route path="/roles" exact component={RolesPage} />
<Route path="/test" exact component={Test} />
<Footer />
</div>
</Router>
However I want the footer element to be hidden if the route path is "/test"
It would be a lot cleaner than writing:
<Route path="/roles" exact component={Footer} />
<Route path="/rules" exact component={Footer} />
<Route path="/" exact component={Footer} />
If anyone knows the function to do this it would be greatly appreciated.
You could create a higher-order component that renders a component with a footer and then you could render that higher-order component at all the paths other than /test.
Higher-order component just takes a component that should be displayed with a Footer component and returns another component that just renders the wrapped component along with the Footer component.
function WithFooter(WrappedComponent) {
const EnhancedComponent = (props) => {
return (
<>
<WrappedComponent {...props} />
<Footer />
</>
);
};
return EnhancedComponent;
}
After this, instead of exporting PersonList component, you need to export the component returned by calling WithFooter higher-order component as shown below:
function PersonList() {
...
}
export default WithFooter(PersonList);
You need to do the same for other components as well that should be rendered with a Footer.
With higher-order component all set-up, your routes definition don't need to change:
<Router>
<Route path="/" exact component={PersonList)} />
<Route path="/rules" exact component={RulesPage} />
<Route path="/roles" exact component={RolesPage} />
<Route path="/test" exact component={Test} />
</Router>
Alternative solution is to conditionally render the Footer component after checking the URL using window.location or useParams() hook provided by react-router-dom but useParams() will only work if your component is rendered using react router. In your case, you will need window.location.
In your Footer component you could just check if the window.location.pathname includes /test and just return null
Another option incase you are not familiar with the HOC pattern is to render the <Footer/> component inside only those components that need it rather than at the top level.
I am new to the react js. Here I am trying to use the withrouter to get the info of my location.
SO, I have following structure.
index.js
ReactDOM.render(
<App />
, document.getElementById('root'));
App.js
<Provider store={store}>
<div>
<Header />
<Main />
</div>
</Provider>
Main.js
return (
<Router history={history}>
<div>
{this.props.isFetching && <Loading />}
<Switch>
<PrivateRoute exact path="/" component={LandingPage} />
<PrivateRoute exact path="/create-job" component={NewJob} />
<PrivateRoute exact path="/user-jobs" component={JobList} />
<Route exact path="/login" component={Login} />
</Switch>
</div>
</Router>
Now, I am trying to use the withRouter in the Header.js. which is not a part of the Router. SO,
import { withRouter } from "react-router-dom";
export default withRouter(connect(mapStateToProps, { logout })(Header));
I tried using this way. So, it is giving me the following error.
You should not use <Route> or withRouter() outside a <Router>
What is it that I am doing wrong over here ?
You're rendering the Header component (which uses withRouter) outside the Router component. You need to make sure that all the Routes and the components using withRouter need to be a child of Router, at some level in the hierarchy.
In your case, maybe wrap the div in the App with the Router?
Details from source
The error is generated here when Route doesn't get passed a context from its provider. And, withRouter is just a wrapper over Route. The only time the context is not available is when the Route is not nested inside a Router somewhere.
Your issue is that withRouter props get blocked by PureComponent check, put it after connect:
export default connect(mapStateToProps, { logout })(withRouter(Header));
See: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md#important-note
Personally I prefer to have my providers in one place in index.js not App.js, your whole app should be wrapped in Router, not a part of App.js:
const WrappedApp = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render(WrappedApp, document.getElementById('root'));
You need to move <Header> component inside <Router> component, otherwise it doesn't work as the error says.
So you want to do 2 things, inject the state in the Header, and inject routing information in Header.
If you are outside of the <Router/> component you will not be able to use withRouter(, simply because you will not have any match props to link to your compoonent.
What you need to do is to create something called layouts.... and use the layouts in the page definition like this.
Lets say you have this Route <PrivateRoute exact path="/" component={LandingPageContainer} />
Now inside the LandingPage you need to do something like
landingPageContainer.js
render() {
return (
<SimpleLayout header={<Header ...this.props/> footer={<Footer ...this.props/>}>
<LandingPageDummyPage ...this.props/>
<SimpleLayout/>
);
}
export default connect(withRouter(LandingPageContainer);
this will copy all the props passed to the Simple Layout to your LandingPageLayout, header and footer
simpleLayout.js
render() {
return (
<div>{this.props.header} </div>
<div>{this.props.children} </div>
<div{this.props.footer} </div>
);
}
export withRouter(SimpleLayout);
advice . read the router documentation and try to understand whats the purpose if it... you didn`t quite get it :) ...
I have the next routes on main component of my app:
<div>
<h1><Link to="/">Home</Link></h1>
<Switch>
<Route exact path="/" component={FirstPage} />
<Route exact path="/:language?/second" component={SecondPage} />
<Route exact path="/:language?/account" component={AccountPage} />
<Route exact path="/:language?/add" component={AddNewPage} />
<Route component={NoMatch} />
</Switch>
</div>
I need to add in each child component checking this.props.match.params.language (this is react-router props) in order to set the current language. But white this code in each componentWiilMount looks wired on my mind. Even I put this checking in a single function and will call it every componentWiilMount and pass this.props.match.params.language props to it, anyway it a mess of code. For example, if I have 100 routes I need to add this checking 100 times.
Also, I think about adding this code to the main component lifecycle, and it will be called when the page changed, but I do not have react-router props here.
Maybe you know a better solution for this?
You may want to try nesting your routes. You could have one parent route component that manages the language then nests child route components:
function Root() {
return (
<div>
<h1><Link to="/">Home</Link></h1>
<Route path="/:language?" component={LanguageSelector}/>
</div>
);
}
class LanguageSelector extends React.Component {
componentDidMount() {
// Manage language (if specified)
}
render() {
return (
<Switch>
<Route .../>
<Route .../>
</Switch>
);
}
}
I installed react-router-dom and use this code for routing, But i have error :
import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Switch } from 'react-router-dom';
class Home extends React.Component{
render(){
return(
<h1>Home</h1>
);
}
}
class About extends React.Component{
render(){
return(
<h1>About</h1>
);
}
}
ReactDOM.render(
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
</Switch>,
document.getElementById('main')
);
What's the right way for routing in reactjs ?
tnx
Wrap BrowserRouter around your Switch like below,
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</Switch>
</BrowserRouter>
Here is the working code demo in codesandbox.
You didn't import BrowserRouter
You should wrap your <Switch> arround <BrowserRouter> tag
Better use a component than trying to render a <Switch> element
You may find anything your looking for on this link :
https://reacttraining.com/react-router/web/guides/philosophy
Also i made a quick pen : https://codepen.io/FabienGreard/pen/KZgwKO?editors=1010
Kay Concepts
<BrowserRouter> is needed because
Each router creates a history object, which it uses to keep track of the current location and re-render the website whenever that changes
A React Router component that does not have a router as one of its ancestors will fail to work.
Router components only expect to receive a single child element. To work within this limitation, it is useful to create an component that renders the rest of your application.
<Route>
The component is the main building block of React Router. Anywhere that you want to only render content based on the location’s pathname, you should use a element.
<Path>
When the current location’s pathname is matched by the path, the route will render a React element.
<Switch>
You can use the component to group s.
The will iterate over its children elements (the routes) and only render the first one that matches the current pathname.
I think you should create different component for Routes.
I'll just explain general project structure here
You can create component to hold <Header> and <MainContent>
As <Header> will be same througout the application and it will not change if path changes. You can include routes in <MainContent> which will be updated if path changes.
MainContent.js
import { Switch, Route } from 'react-router-dom';
const MainContent = () => (
<main>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
</Switch>
</main>
)
export default MainContent;
Layout.js
class Layout extends Component {
render() {
return (
<div className={classes.root}>
<Header />
<MainContent />
</div>
);
}
Now you can use <BrowserRouter>to wrap your <Layout> in App.js . or you can use it in <MainContent> as well
App.js
import { BrowserRouter } from "react-router-dom";
class App extends Component {
render() {
return(
<BrowserRoter>
<Layout />
</BrowserRouter>
);
}
}