I have installed react-router-domV6-beta. By following the example from a website I am able to use the new option useRoutes I have setup page routes and returning them in the App.js file.
After saving I am getting the following error:
Error: useRoutes() may be used only in the context of a component.
I am wondering If I am missing something here? I have created the pages inside the src/pages folder.
My code:
import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom';
// Pages
import Home from './pages/Home';
import About from './pages/About';
import Services from './pages/Services';
import Gallery from './pages/Gallery';
import Prices from './pages/Prices';
import Contact from './pages/Contact';
const App = () => {
const routes = useRoutes([
{ path: '/', element: <Home /> },
{ path: 'o-nama', element: <About /> },
{ path: 'usluge', element: <Services /> },
{ path: 'galerija', element: <Gallery /> },
{ path: 'cjenovnik', element: <Prices /> },
{ path: 'kontakt', element: <Contact /> }
]);
return routes;
};
export default App;
You should have a <BrowserRouter> (or any of the provided routers) higher up in the tree. The reason for this is that the <BrowserRouter> provides a history context which is needed at the time the routes are created using useRoutes(). Note that higher up means that it can't be in the <App> itself, but at least in the component that renders it.
Here's what your entry point could look like:
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'),
);
I think the problem is that you still need to wrap routes (Routes / useRoutes) inside a Router element.
So an example would look something like this:
import React from "react";
import {
BrowserRouter as Router,
Routes,
Route,
useRoutes,
} from "react-router-dom";
const Component1 = () => {
return <h1>Component 1</h1>;
};
const Component2 = () => {
return <h1>Component 2</h1>;
};
const App = () => {
let routes = useRoutes([
{ path: "/", element: <Component1 /> },
{ path: "component2", element: <Component2 /> },
// ...
]);
return routes;
};
const AppWrapper = () => {
return (
<Router>
<App />
</Router>
);
};
export default AppWrapper;
Refactor according to your needs.
its means in Your index js Or App JS wrap with BrowserRouter like this
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter> // Like This here I am using
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root"),
);
Mention below code in index.js
import { BrowserRouter as Router } from "react-router-dom";
Just want to report on a similar issue -- as of writing (v6.2.1), it seems you actually encounter this error as well if you are importing from react-router instead of react-router-dom. A costly typo on my part.
I.e., make sure you are importing Routes and Route from react-router-dom and NOT react-router
// This is deceptively valid as the components exist, but is not the intended usage
import { Routes, Route } from 'react-router';
// This works and is the intended usage
import { Routes, Route } from 'react-router-dom';
Code: index.js
import {BrowserRouter as Router} from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById("root")
);
app.js
function App() {
return (
<>
<Routes>
<Route path ="/" element={<Main />} />
<Route path ="gigs" element={<Gigs />} />
</Routes>
</>
);
}
Try to add your routes in index.js not in App.js. Your App.js is called from index.js. In the index.js your external page is called like this
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<Navbar />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);
> Following codes works since react-router-dom syntax changed because of React 18.
import logo from './logo.svg';
import './App.css';
import Header from './components/Header';
import Login from './components/Login';
import {
BrowserRouter as Router,
Routes,
Route,
useRoutes,
} from 'react-router-dom';
import Signup from './components/Signup';
function AppRoutes() {
const routes = useRoutes(
[
{path:'/',element:<Login/>},
{path:'/signup',element:<Signup/>}
]
)
return routes;
}
function App(){
return (
<Router>
<Header/>
<AppRoutes />
</Router>
)
}
export default App;
Try
const Routes = () => useRoutes([])
and then wrap it like this in App.js
<BrowserRouter>
<Routes />
</BrowserRouter>
It worked for me
I got this error because I had two different versions of react-router-dom being bundled.
If you're using npm/yarn workspaces, check that there is only one installed version of react-router-dom in the top-level node_modules folder
My content is displaying normally until I add route and switch. After that my content doesn't display and I cant understand why. I downloaded react-route-dom too.
code from App.js
import './App.css';
import Navbar from './components/Navbar.js'
import HomeView from './components/HomeView.js'
import AboutView from './components/AboutView.js'
import {Switch, Route} from 'react-router-dom'
function App() {
return (
<div>
<Switch>
<Navbar/>
<Route path="/" exact>
<HomeView/>
</Route>
<Route path="/about" component={AboutView}/>
</Switch>
</div>
);
}
export default App;
code from the components
const HomeView = () => {
return(
<div>
<h1>Home</h1>
</div>
)
}
export default HomeView;
const AboutView = () => {
return (
<div>
<h1>About</h1>
</div>
)
}
export default AboutView;
code from index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
My routing component looks like this:
import { Link, Route, Switch } from 'react-router-dom';
import Nav from 'react-bootstrap/Nav'
import AllWorkouts from './Workout/AllWorkouts/AllWorkouts';
import WorkoutCreate from './Workout/WorkoutCreate/WorkoutCreate';
import WorkoutDetails from './Workout/WorkoutDetails/WorkoutDetails';
import WorkoutEdit from './Workout/WorkoutEdit/WorkoutEdit';
const Main = () => {
return (
<Switch>
<Route path="/workout/:id/edit" componnet={WorkoutEdit} />
<Route path="/workout/:id/details" componnet={WorkoutDetails} />
<Route path="/workout/create" componnet={WorkoutCreate} />
<Route path="/workout/all" component={AllWorkouts} />
</Switch>
);
}
export default Main;
I have included BrowserRouter in index.js and the only route that is matching is path="/workout/all". I cannot call any of the other routs with Link or directly in the URL.
When I call /workout/all I can see the component with all the other routes nothing happens.
Thank you!
Below is the other component and I do not see any misspelling error:
import { Link, Route, Switch } from 'react-router-dom';
import Button from 'react-bootstrap/Button'
const AllWorkouts = () => {
return (
<div>
<Link to="/workout/create">
<Button variant="outline-primary">Create new workout</Button>{' '}
</Link>
<h1>Hello from AllWorkouts</h1>
</div>
);
}
export default AllWorkouts;
You have misspelled component in the other routes
mport { Link, Route, Switch } from 'react-router-dom';
import Nav from 'react-bootstrap/Nav'
import AllWorkouts from './Workout/AllWorkouts/AllWorkouts';
import WorkoutCreate from './Workout/WorkoutCreate/WorkoutCreate';
import WorkoutDetails from './Workout/WorkoutDetails/WorkoutDetails';
import WorkoutEdit from './Workout/WorkoutEdit/WorkoutEdit';
const Main = () => {
return (
<Switch>
<Route path="/workout/:id/edit" component={WorkoutEdit} />
<Route path="/workout/:id/details" component={WorkoutDetails} />
<Route path="/workout/create" component={WorkoutCreate} />
<Route path="/workout/all" component={AllWorkouts} />
</Switch>
);
}
export default Main;
I am stuck with react-router routing. I am getting the error:
Warning: [react-router] Location "/add" did not match any routes`
// conf.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link} from "react-router-dom";
import add from './add';
import { createBrowserHistory } from 'history';
import confv1 from './confv1';
var button =React.createElement(Link, {
to: "/add"
}, React.createElement("button", {
type: "button"
}, "Add a project"));
export default class Root extends Component {
render() {
return (
React.createElement(Router, {
history: createBrowserHistory()
}, React.createElement(Route, {
path: "/conf",
component: confv1
}, React.createElement(Route, {
component: conf
}), React.createElement(Route, {
path: "/add",
component: add
})
)));
// );this is the conf page
and this is the add page when I refresh it I got the error "Warning: [react-router] Location "/add" did not match any routes`"
}
}
`
I resolved the error with a routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import conf from './conf';
import add from './add';
export default (
<Route path="/" component={App}>
<IndexRoute component={conf} />
<Route path="/conf" component={conf} >
<IndexRoute component={add} />
<Route path="/add" component={add} />
</Route>
</Route>
);
//index.js
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Router, BrowserRouter } from 'react-router';
import routes from './routes';
import {browserHistory} from 'react-router';
const history = require("history").createBrowserHistory();
render(
<Router history={browserHistory} routes={routes} />, document.getElementById('root')
)
but when I refresh the add page nothing shows in the contententer image description here
I noticed from your code snippet that you are using two different npm packages, and I am wondering if that is part of the issue.
under Config.js you called:
import { BrowserRouter as Router, Route, Link} from "react-router-dom";
Then under index.js you called:
import {Router, BrowserRouter } from 'react-router';
if that doesn't fix the issue could you create a codesandbox so I can take a look?
https://codesandbox.io/
Here is more information about the two npm packages you were trying to use:
https://www.npmjs.com/package/react-router
https://www.npmjs.com/package/react-router-dom
good luck!
//app.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import createHistory from 'history/createBrowserHistory';
import { Route } from 'react-router';
import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux';
import App from './components/app.js';
import reducers from './reducers';
const history = createHistory();
const middleware = routerMiddleware(history);
// Add the reducer to your store on the `router` key
// Also apply our middleware for navigating
const store = createStore({
...reducers,
router: routerReducer
},
applyMiddleware(middleware)
);
const About = () => {
return (<div>
Will this work?
</div>);
}
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<Route exact path="/" component={App}/>
<Route path="/about" component={About}/>
</div>
</ConnectedRouter>
</Provider>
, document.querySelector('#app'));
Here is my reducers/index.js code.
//reducers/index.js
import { combineReducers } from 'redux';
import { mobileLinks } from './reducer_header';
import UserDetailsReducer from './reducer_user_details';
const rootReducer = combineReducers({
mobileLinks,
userDetails: UserDetailsReducer
});
export default rootReducer;
What do I do to fix this? I'm unable to find any examples for the new version of react-router-redux. I've tried moving the routerReducer to reducers/index.js but that didn't work either. Can someone please help?
Most likely you do not have Babel set to transpile the Object Spread Operator, you can read up on it here.
You can simply install the Babel "Object rest spread transform" preset like so:
npm install --save-dev babel-plugin-transform-object-rest-spread
And add it to your list of plugins:
{
"plugins": [
// Other plugins...
"transform-object-rest-spread"
]
}