Component cannot listen to react-router - javascript

I have a component that is used persistently across my spa. I want it to be aware of my router and the various paths that my spa is on. Is there an easy way to do this, or do I have to bandaid some redux (or something similar) state solution that is always listening to my router changes? Thanks! You can see the below for an example.
index.jsx:
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { Route, Switch } from 'react-router-dom';
import { history, store } from './redux/store';
import Navigation from './navigation';
const UserReport = () => <h2>User Report</h2>;
const UserPage = () => <h2>User Page</h2>;
const Routes = () => (
<React.Fragment>
<Route component={Navigation} />
<Switch>
<Route exact path="/users/:startDate" component={UserReport} />
<Route exact path="/users/:userId" component={UserPage} />
</Switch>
</React.Fragment>
);
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>, document.getElementById('app'),
);
navigation.jsx:
import React from 'react';
import { withRouter } from 'react-router-dom';
const Navigation = (props) => {
console.log(props.match.path);
// expected: "/users/:startDate"
// received: "/"
return (
<h2>Navigation</h2>
);
};
export default withRouter(Navigation);

Since the Navigation route doesn't have any path specified, it always matches whatever path you're on but the match.path only shows you the minimum path required to match for the navigation. That's why it's always /.
You can use location.pathname but it gives you the matched value and not the matched path.
const Navigation = props => {
console.log(props.location.pathname);
// prints `/users/1` if you're on https://blah.com/users/1
// prints `/users/hey` if you're on https://blah.com/users/hey
return <h2>Navigation</h2>;
};
Not sure that's what you want but if you expand what exactly you're trying to achieve, maybe I can help more.
Moreover, your second route to path="/users/:userId" overshadows the first route. Meaning there is no way to tell if hey in /users/hey is startDate or userId. You should introduce a separate route like path="/users/page/:userId".

I ended up using this react-router github discussion as my solution.
An example of my implementation:
index.jsx:
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { Route, Switch } from 'react-router-dom';
import { history, store } from './redux/store';
import Layout from './layout';
const home = () => <h2>Home Page</h2>;
const users = () => <h2>Users</h2>;
const userPage = () => <h2>User Page</h2>;
const layoutRender = component => route => <Layout component={component} route={route} />;
const Routes = () => (
<Switch>
<Route exact path="/" component={layoutRender(home)} />
<Route exact path="/users" component={layoutRender(users)} />
<Route exact path="/users/:id" component={layoutRender(userPage)} />
</Switch>
);
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>, document.getElementById('app'),
);
layout.jsx:
import React from 'react';
const Layout = (props) => {
const {
component: Component,
route,
} = props;
return (
<div>
<h1>This is the layout</h1>
<Component route={route} />
</div>
);
};
export default Layout;

Related

React Router v6.4 useNavigate(-1) not going back

I created a component in my project that consists of a simple button that returns to the previous page, using useNavigate hook.
As it is written in the documentation, just passing -1 as a parameter to the hook would be enough to go back one page. But nothing happens.
The component code:
import { useNavigate } from 'react-router-dom'
import './go-back.styles.scss'
const GoBack = () => {
const navigate = useNavigate()
const handleClick = () => {
navigate(-1)
}
return (
<button
className='go-back'
onClick={handleClick}
>
go back
</button>
)
}
export default GoBack
The app.js code:
import { lazy, Suspense } from 'react'
import { Routes, Route } from 'react-router-dom'
import Header from '../components/header/header.component'
import Footer from '../components/footer/footer.component'
import './App.scss'
const App = () => {
const HomePage = lazy(() => import('../pages/home/home.page'))
const SearchPage = lazy(() => import('../pages/search/search.page'))
const MostraPage = lazy(() => import('../pages/mostra/mostra.page'))
const AuthPage = lazy(() => import('../pages/auth/auth.page'))
const AccountPage = lazy(() => import('../pages/account/account.page'))
const PrenotaPage = lazy(()=> import('../pages/prenota/prenota.page'))
const SectionPage = lazy(() => import('../pages/section/section.page'))
return (
<div className='app'>
<Header />
<Suspense fallback={<span>Loading...</span>}>
<Routes>
<Route exact path='/' element={<HomePage />} />
<Route exact path='/auth:p' element={<AuthPage />} />
<Route exact path='/search' element={<SearchPage />} />
<Route exact path='/search:id' element={<SectionPage />} />
<Route exact path='/mostra' element={<MostraPage />} />
<Route exact path='/prenota' element={<PrenotaPage/>} />
<Route exact path='/profile' element={<AccountPage />} />
<Route exact path='*' element={<span>Page not found</span>} />
</Routes>
</Suspense>
<Footer />
</div>
)
}
export default App
The index.js code:
import { createRoot } from 'react-dom/client'
import { Provider } from 'react-redux'
import store, { persistor } from './redux/store/store'
import App from './app/App'
import reportWebVitals from './reportWebVitals'
import { PersistGate } from 'redux-persist/integration/react'
import { BrowserRouter } from 'react-router-dom'
const container = document.getElementById('root')
const root = createRoot(container)
root.render(
<BrowserRouter>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</BrowserRouter>
)
reportWebVitals()
I thank in advance anyone who tries to help.
In the project, when rendering to another page I used the useNavigate hook and passed { replace: true } as the second parameter.
However, in this way the navigation will replace the current entry in the history stack instead of adding a new one by not then making the GoBack component work properly.
So it was enough to remove { replace: true } from the calls to useNavigate and now it works.

React router dom routing to ItemDetail

I am doing a personal React.js project. I am trying to use react-router-dom, but I haven't been able to make it work. I did the BrowserRouter in the App.js. Till there the app works fine, but I cannot make the routing redirect dynamically to a map item. I tried to follow the documentation and some tutorials unsuccesfully. The data comes from the Star Wars API This is the code:
App.js:
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<Router>
<>
<Navbar />
<Routes>
<Route exact path='/' element={<Home />} />
</Routes>
<Routes>
<Route exact path to='/:movieId' element={<MovieDetail />} />
</Routes>
</>
</Router>
);
}
export default App;
ItemDetail:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
const MovieDetail = () => {
const { movieId } = useParams();
const [result, setResult] = useState([]);
const fetchData = async () => {
const res = await fetch("https://www.swapi.tech/api/films/");
const json = await res.json();
setResult(json.result);
}
useEffect(() => {
fetchData();
}, []);
let movieMatch = (result.find(value) => value.properties.title == movieId)
return (
<div>
<h2>
{result
.find((value) => {value.properties.title == movieId})}
</h2>
</div>
);
}
export default MovieDetail;
UPDATE
This is a link to the whole code in codesand with updated App.js
From your code I'm assuming you're using React Router v6 in your project. Try the below code:
import './App.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<BrowserRouter>
<Routes>
<Navbar />
<Route path='/' element={<Home />} />
<Route path=':movieId' element={<MovieDetail />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Checkout React Router's Documentation for more detail.
if you are using index.js as a wrapper for app.js <BrowserRouter /> or <Router /> in your case is not used in app.js it's used in index.js otherwise it will not work
index.js should look like this : -
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
function App() {
return <h1>Hello React Router</h1>;
}
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
**For example just Let's say you are having "/movies" route and you want when ever your app (route = "/") starts / loads up to be redirected to "/movies" **
then wrap the routing logic with *<Switch />* ,make use of Redirect property of router dom to redirect from "/" to "/movies" and use component instead of element to render the corresponding component plus dont wrap with <Routes> </Routes> every time you are doing the route as we used it in index.js
then app.js will be : -
import './App.css';
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import Home from './components/Home';
import MovieDetail from './components/MovieDetail'
import Navbar from './components/Navbar';
function App() {
return (
<>
<Navbar />
<Switch>
<Route exact path='/movies' component={<Home />} />
<Route exact path to='movies/:movieId' component={<MovieDetail />}
// to redirect from "/" to "/movies"
<Redirect from="/" to="/students"></Redirect>
);
}

How to use a hook in React?

I have information in the state (true or false) that I want to display if is true this Navbar component, but when I use the hook, I get an error message:
hook error
My code:
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import store, { history } from './reduxStore';
import AppRouterContainer from './pages/AppRouterContainer';
import Feedback from './pages/feedback/Feedback';
import Navbar from './components/Navbar/Navbar';
import { useTypedSelector } from '../src/hooks/useTypedSelector';
const isAuth = useTypedSelector((state) => state.auth.isAuth);
const App = () => (
<BrowserRouter>
<Provider store={store}>
<ConnectedRouter history={history}>
<AppRouterContainer />
{isAuth && (
<Navbar />
)}
<Feedback />
</ConnectedRouter>
</Provider>
</BrowserRouter>
);
export default App;
You need to create a wrapper component to have access to store in your context (I think your useTypedSelector() hook needs that access).
You can use hooks only inside a function, not just inside a module.
Check out this example:
import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';
import { useTypedSelector } from '../src/hooks/useTypedSelector';
import Navbar from './components/Navbar/Navbar';
import AppRouterContainer from './pages/AppRouterContainer';
import Feedback from './pages/feedback/Feedback';
import store, { history } from './reduxStore';
const NavbarWrapper = () => {
const isAuth = useTypedSelector((state) => state.auth.isAuth);
if (!isAuth) {
return null;
}
return <Navbar />;
};
const App = () => (
<BrowserRouter>
<Provider store={store}>
<ConnectedRouter history={history}>
<AppRouterContainer />
<NavbarWrapper />
<Feedback />
</ConnectedRouter>
</Provider>
</BrowserRouter>
);
export default App;
Also, I think you should move the NavbarWrapper component to a separate file.

React Router Error: You should not use Route outside of Router

I'm just doing some basic routing in my react app and I've done it this way before so I'm pretty confused to as why it isn't working now.
The error I am getting says: You should not use <Route> or withRouter() outside a <Router>
I'm sure this is super basic so thanks for baring with me!
import React from 'react'
import { Route } from 'react-router-dom'
import { Link } from 'react-router-dom'
import * as BooksAPI from './BooksAPI'
import BookList from './BookList'
import './App.css'
class BooksApp extends React.Component {
state = {
books: []
}
componentDidMount() {
this.getBooks()
}
getBooks = () => {
BooksAPI.getAll().then(data => {
this.setState({
books: data
})
})
}
render() {
return (
<div className="App">
<Route exact path="/" render={() => (
<BookList
books={this.state.books}
/>
)}/>
</div>
)
}
}
export default BooksApp
You need to setup context provider for react-router
import { BrowserRouter, Route, Link } from 'react-router-dom';
// ....
render() {
return (
<BrowserRouter>
<div className="App">
<Route exact path="/" render={() => (
<BookList
books={this.state.books}
/>
)}/>
</div>
</BrowserRouter>
)
}
Side note - BrowserRouter should be placed at the top level of your application and have only a single child.
I was facing the exact same issue. Turns out that i didn't wrap the App inside BrowserRouter before using the Route in App.js.
Here is how i fixed in index.js.
import {BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
document.getElementById('root')
);

Access server props from within redux?

I'm trying to use redux, react-engine, and react-router.
The issue or question I have is that react-engine provides an object of props that come from the server. How do I access these props from within my ProvidedApp?
ProvidedApp.js
import React from 'react'
import { connect, Provider } from 'react-redux'
import App from './app'
import { mapStateToProps, mapDispatchToProps, store } from './redux-stuff'
// Connected Component
let ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App)
let ProvidedApp = () => (
<Provider store={store}>
<ConnectedApp/>
</Provider>
)
export default ProvidedApp
Routes.js
import React from 'react'
import { Router, Route } from 'react-router'
import Layout from './views/Layout'
import App from './views/ProvidedApp'
module.exports = (
<Router>
<Route path='/' component={Layout}>
<Route path='/app' component={App} />
<Route path='/app/dev' component={App} />
</Route>
</Router>
)
I also think my configuration is a little wonky, I couldn't get Provider working any other way. If theres a way to have Provider wrap the Router I'd love to get that working.
Here's some code of what it looks like when I move Provider above Router
ConnectedApp.js
import React from 'react'
import { connect, Provider } from 'react-redux'
import App from './app'
import { mapStateToProps, mapDispatchToProps} from './redux-stuff'
let ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App)
export default ConnectedApp
Routes.js
import React from 'react'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router'
import { store } from './redux-stuff'
import Layout from './views/Layout'
import App from './views/ConnectedApp'
module.exports = (
<Provider store={store}>
<Router>
<Route path='/' component={Layout}>
<Route path='/app' component={App} />
</Route>
</Router>
</Provider>
)
I get this error:
Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(App)".
Update
I found that I can access from he code in my first example within ProvidedApp. But I have no clue how I'm supposed to pass it into Redux.
let ProvidedApp = (props) => {
console.log(props)
return (
<Provider store={store}>
<ConnectedApp/>
</Provider>
)
}
Seems like I need to wrap the reducer and store and pass in the ServerProps to the default state like this.
let getDefaultState = (serverProps) => {
return {
'appName': serverProps.appName
}
}
let getReducer = (serverProps) => {
let defaultState = getDefaultState(serverProps)
return (state = defaultState, action) => {
}
}
let getStore = (serverProps) => {
let reducer = getReducer(serverProps)
return store = createStore(reducer)
}
let ConnectedApp = connect(
mapStateToProps,
mapDispatchToProps
)(App)
let ProvidedApp = (serverProps) => {
return (
<Provider store={getStore(serverProps)}>
<ConnectedApp/>
</Provider>
)
}
This is super ugly :/

Categories