I am new to react and still learning.
I am trying to add nested routes in my react project, so that a content of div changes based on the route.
Following are my components :-
//index.js
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
library.add(faIgloo);
ReactDOM.render(<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
serviceWorker.unregister();
// app.js
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from './components/login/login.js'
import Protected from './components/protected/protected.js'
import './App.css';
class App extends Component {
render() {
return (
<Switch>
<Route exact path="/protected" component={Protected}/>
<Route path="/login" component={Login}/>
</Switch>
);
}
}
export default App;
//protected.js
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Header from './header/header.js';
import './protected.css';
import CafePreview from './cafepreview/cafepreview.js'
class Protected extends Component {
render() {
const {match} = this.props;
return (
<div>
<Header></Header>
{/*<Preview/>*/}
<Switch>
<Route path='/protected/cafepreview' component={CafePreview}/>
</Switch>
</div>
);
}
}
export default Protected
// cafepreview.js
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import './preview.css';
console.log("here");
class CafePreview extends Component {
render() {
return (
<div>
<div>
<i class="fa fas fa-arrow-left"></i>
<span> BACK TO ALL CAFES </span>
</div>
</div>
);
}
}
export default CafePreview
When i open '/protected' i can see the header coming, but when i try to open '/protected/cafepreview' i see an empty page instead of header with cafe preview html.
I tried some options mentioned in this stackoverflow thread Multiple Nested Routes in react-router-dom v4 but none of them worked.
I hope i have explained my problem clearly.
Check documentation https://reacttraining.com/react-router/web/api/Route/exact-bool. Remove exact from the route in the App component and it will start working.
its because you have set exact in the app.js file. Remove it from the particular route. It'll work
Related
I'm trying to set up routing but for some reason, it returns a blank page and renders nothing.
I'm using router version 6.3.0
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter><App /></BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
// --------------------------------------------- //
// App.js
import React, { Component, Fragment } from "react";
import { Route } from "react-router-dom";
import Header from "./components/Landing/Header"
import Landing from "./components/Landing/Landing";
import Footer from "./components/Landing/Footer";
class App extends Component {
render() {
return (
<Fragment>
<Header />
<Route path="/landing">
<Landing />
</Route>
<Footer />
</Fragment>
);
}
}
export default App;
// --------------------------------------------- //
// Landing.js
import Body from './Body'
function Landing(props) {
return (
<Body>
<div className="Landing">
Landing Context
</div>
</Body>
)
}
export default Landing;
So when I visit http://localhost:3000/landing nothing is rendered, and when I try http://localhost:3000 nothing is rendered either.
If I remove the <Route></Route> part in App.js, it renders, but on any URL. What do I miss?
As the OP is using react-router-dom v6
Instead of children, it is expecting element props to render the component.
https://reactrouter.com/docs/en/v6/getting-started/overview#configuring-routes
In app.js wrap your route in router like this
import React, { Component, Fragment } from "react";
import { Router, Route } from "react-router-dom";
import Header from "./components/Landing/Header"
import Landing from "./components/Landing/Landing";
import Footer from "./components/Landing/Footer";
class App extends Component {
render() {
return (
<Fragment>
<Header />
<Router>
<Route path="/landing">
<Landing />
</Route>
</Router>
<Footer />
</Fragment>
);
}
}
export default App;
react-router v6 has some breaking changes, it replaced Switch with Routes component:
/ index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter><App /></BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
// --------------------------------------------- //
// App.js
import React, { Component, Fragment } from "react";
import { Routes, Route } from "react-router-dom";
import Header from "./components/Landing/Header"
import Landing from "./components/Landing/Landing";
import Footer from "./components/Landing/Footer";
class App extends Component {
render() {
return (
<Fragment>
<Header />
<Routes>
<Route path="/landing" element={<Landing />}/>
</Routes>
<Footer />
</Fragment>
);
}
}
export default App;
https://reactrouter.com/docs/en/v6/getting-started/overview
If your are using react-router version < 6 then you have to add Switch element imported from react-router-dom above your Route Element -
// App.js
import React, { Component, Fragment } from "react";
import { Route, Switch } from "react-router-dom";
class App extends Component {
render() {
return (
<Fragment>
<Switch>
<Route path="/landing">
<div>On LAnding Page</div>
</Route>
</Switch>
</Fragment>
);
}
}
export default App;
And if you are using react-router > 6 then you have to replace Switch with Routes and place your component you want to render inside element property of Route . The code should be similar to following -
// App.js
import React, { Component, Fragment } from "react";
import { Route, Routes } from "react-router-dom";
class App extends Component {
render() {
return (
<Fragment>
<Routes>
<Route path="/landing"
element={<div>On Landing Page</div>}>
</Route>
</Routes>
</Fragment>
);
}
}
export default App;
I am learning React, so this question may make no sense but I want to learn it.
I have index.html page and I want to jump to Components.html page.
RouteToComponent.jsx
import React from 'react';
class RouteToComponents extends React.Component {
render() {
return (
<div>
Components
</div>
);
}
}
export default RouteToComponents;
RouteToComponent.jsx is called inside index.jsx
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import RouteToComponents from './BasicJSX/RouteToComponents.jsx';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
<RouteToComponents />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
export default App;
components.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return (
<div>
Entered Components HTML!!!
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
export default App;
But when I click on a tag URL changes but the page remains same.
Wrap your App.js with Router and define Routes. <Route /> allows us to define all paths of our Application.
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import RouteToComponents from './RouteToComponents.jsx';
import AnyComponent from './AnyComponent';
import App from './App.jsx';
return (
<Router>
<RouteToComponents />
<Switch>
<Route exact path="/" component={App} />
<Route path="/Components/Components.html" component={AnyComponent} />
</Switch>
</Router>
);
Now in your Component where you want to use Link.
In React <Link /> is used instead of anchor.
import { Link } from "react-router-dom";
return (
<div>
<Link to="Components/Components.html">Components</Link>
<Link to="/">Home</Link>
</div>
);
to in Link attribute is similar to href in anchor.
Remember:
npm i react-router-dom
to attribute of Link must be similar to the path defined in App.js Route.
Because when you click on Link it matches Routes in App.js
I am trying to route to a class component but it gives me an error. When I change the component to a functional component, the routing works. How do I route to class components?
I am new to using react-router. I first had a functional component to route to. But once I realized the component needs to be a class, I changed it to a class and now the routing shows
"Cannot GET /explore/words'.
index.js
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.querySelector("#root")
);
App.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./pages/HomePage";
import ExplorePage from "./pages/ExplorePage";
function App() {
return (
<Router>
<div>
<header>
<nav>Course Finder</nav>
</header>
<Route path="/" component={HomePage} />
<Route path="/explore/:campus" component={ExplorePage} />
</div>
</Router>
);
}
export default App;
Explore.js
import React, { Component } from "react";
class ExplorePage extends Component {
render() {
return (
<div>
<h1>Explore</h1>
</div>
);
}
}
export default ExplorePage;
Expected result was to see the 'Explore' heading.
I get 'Cannot GET /explore/words' instead.
This is working fine, all you have to do is add /explore/one to url to see the route working.
https://codesandbox.io/embed/nervous-wood-cw8cd
I'm trying to use React Router 4.2.2 in order to load a component called PostFocus whenever I click on a 'Card' component, with a Link wrapped around it. When I click on a 'Card' the path changes correctly, but the PostFocus component isn't rendered. Have I done something wrong or missed something out in the Route? I can't figure it out.
Here is the code:
class PostsList extends React.Component {
render() {
var createCards = this.props.posts.map((post, i) => {
return (
<div key={i}>
<Link to={`/${post.id}`}>
<Card title={post.title} subtitle={post.subtitle} date={post.date} id={post.id}/>
</Link>
<Route exact path={`/${post.id}`} render={(post) => (
<PostFocus content={post.content}/>
)}/>
</div>
);
});
return (
<div>
{createCards}
</div>
);
}
App Component:
import React from 'react';
import PostsList from '../containers/posts_list.js';
import {withRouter} from 'react-router';
class App extends React.Component {
render() {
return(
<div>
<PostsList />
</div>
);
}
}
export default withRouter(App);
index.js code:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App.jsx';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, document.getElementById('root'));
I was also facing the same problem. I fixed it with a trick.
You might have BrowseRouter in your App.js or index.js, I had it in my index.js like this :
ReactDOM.render(<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'))
I changed it to :-
ReactDOM.render((
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
), document.getElementById('root'))
and it tricked, actually we are keeping the router look over our complete application by doing this, thus it also checks up with the routing path and automatically renders the view. I hope it helps.
Note:- Do not forget to import Route in your index.js
#Tom Karnaski
Hi... Sorry for the late reply, I was not getting time to work on it.. Your code is running in my system, I didn't had access to push a branch in your repo.. make your App.js like below.. it will work for sure..
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Navbar from './Components/Navbar/Navbar';
class App extends React.Component {
render() {
return (
<Router>
<div className="App">
<Route component={Navbar}/>
</div>
</Router>
);
}
}
export default App;
I solved this problem simply use tag instead of Link helper. Not sure is it right or not, but it works for me, hope it will helps anybody else.
First off, I have read through just about every example I can find and looked through various boilerplates to see how others have done this. I am having issues loading pages when clicking <Link>'s with react-router v4. I have also installed the package react-router-connected and have been trying that out as well but no improvement can be seen (however it shows the changes in the redux-logger which is nice).
Currently, the url updates just fine and if I manually change the url and press enter, then the next page will load. But, it will not redirect if I click a link. I am also using create-react app for the project, just for your reference. My actual app is setup as the exact example from usage with react-router in the official redux docs. For simplicity, I have changed my routes to only include links to basic components that do nothing but redirect to one another.
Root.js which houses my routes
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router'
// import App from './App';
import NewComponent from './NewComponent';
import OldComponentent from './OldComponent';
const Root = ({ store, history }) => (
<Provider store={store}>
<ConnectedRouter history={history}>
<Router>
<Switch>
<Route exact path='/' component={OldComponentent}/>
<Route path='/new' component={NewComponent}/>
{/* <Route path='/' component={App}/>
<Route path='/:filter' component={App}/> */}
</Switch>
</Router>
</ConnectedRouter>
</Provider>
)
export default Root;
Home component
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';
class OldComponent extends React.Component {
redirectPage = () => { this.props.dispatch(push('/new')); };
redirectPage1 = () => { this.props.dispatch(push('/')); };
render() {
return (
<div>
OLD COMPONENT
<Button onClick={this.redirectPage}>Redirect new</Button>
<Button onClick={this.redirectPage1}>Redirect /</Button>
<Link to='/new'>Redirect Link</Link>
</div>
)
}
}
export default withRouter(connect()(OldComponent));
Other basic component for redirection purposes
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';
class NewComponent extends React.Component {
redirectPage = () => { this.props.dispatch(push('/')); };
redirectPage1 = () => { this.props.dispatch(push('/new')); };
render() {
return (
<div>
NEW COMPONENT
<Button onClick={this.redirectPage}>Redirect /</Button>
<Button onClick={this.redirectPage1}>Redirect new</Button>
<Link to='/new'>Redirect Link</Link>
</div>
)
}
}
export default withRouter(connect()(NewComponent));
As you can see, they are essentially the same component with minor differences. The url will change to /new or / and will also update the pathname found in the ##router/LOCATION-CHANGE state objects created by react-router-connected package. The url will also change by clicking the <Link> tag but with no redirect.
Any help on how to approach this would be greatly appreciated.
The comment posted by #Supertopoz works this.props.history.push('/pathname') works. However, after setting that up, the <Link> now works as well. I am also using withRouter (which I was before) throughout, so that was another important factor in egtting it to work.