Navigation issues: this.props history appears undefined - javascript

I am unable to go to another page because this.props.history appears undefined. Below is a screenshot of the error that I see. Note that I rendered my welcome component using this.props.history.push("/welcome") from the login component and it worked fine then.
This is my App.js
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Login from "./Components/Login";
import "./App.css";
import Signup from "./Components/Signup";
import Welcome from "./Components/Welcome";
import RecruiterPage from "./Components/Common/RecriterPage";
function App() {
return (
<Router>
<div className="App">
<Route exact path="/signup" component={Signup} />
<Route exact path="/" component={Login} />
<Route exact path="/welcome" component={Welcome} />
<Route exact path="/recruiter" component={RecruiterPage} />
</div>
</Router>
);
}
export default App;

My best guess is that the component you are trying to navigate from is a child component of a parent component that may or may not have access to history, hence has no access to the history props.
There are two ways to solving this:
1. Pass history as a props from the parent to the child component OR
2. Do this on the said component:
import { withRouter } from 'react-router-dom'
...and when exporting the component, wrap it in withRouter e.g.
export default withRouter(ComponentName)

Related

React Router won't load pages without first loading the home page

I am using React Router to navigate to different pages, each one being a different React Component. If I go to the home page first (e.g. /) then click a Link to take me to a different component (e.g. /new-guide), it renders fine. However, when I push the project to production using AWS or Netlify, accessing any component fails without first going to the home component.
Here's what it looks like in action. If you visit https://www.kelv.me/ then click the 'Gap Year' guide, the gap year component renders correctly. However, if you close the tab and try to visit https://www.kelv.me/gap-year directly, a 'Page not found' error occurs.
Here's my App.js:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import GapYear from './components/GapYear';
function App() {
return (
<Fragment>
<Router>
<Fragment>
<div id='content'>
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/gap-year' component={GapYear} />
</Switch>
</div>
</Fragment>
</Router>
</Fragment>
);
}
export default App;
And here's my index.js:
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from 'react-router-dom';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);

Migrate 'react-router' into 'react-router-dom' (v4)

I am learning React Routing and I am watching this tutorial:
https://www.youtube.com/watch?v=1iAG6h9ff5s
Its 2016 tutorial so I suppose something changed because 'react-router' not working anymore and I am supposed to use 'react-router-dom'.
I found that I must uninstall 'history' and 'react-router' and use 'react-router-dom' instead, but It not working as expected when I change it.
How to edit this to make it working with 'react-router-dom'?
import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, IndexRoute, hashHistory} from "react-router";
import Layout from "./pages/Layout";
import Archives from "./pages/Archives";
import Featured from "./pages/Featured";
import Settings from "./pages/Settings";
const app = document.getElementById('app');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Featured}></IndexRoute>
<Route path="archives" component={Archives}></Route>
<Route path="settings" component={Settings}></Route>
</Route>
</Router>,
app);
My edit:
import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";
import Layout from "./pages/Layout";
import Archives from "./pages/Archives";
import Featured from "./pages/Featured";
import Settings from "./pages/Settings";
const app = document.getElementById('app');
ReactDOM.render(
<Router>
<Route path="/" component={Layout}>
<Route path="/featured" component={Featured}/>
<Route path="/archives" component={Archives}/>
<Route path="/settings" component={Settings}/>
</Route>
</Router>,
app);
Also pushState not working...
Layout.js
import React from "react";
import {Link} from "react-router-dom";
export default class Layout extends React.Component {
navigate() {
this.props.history.pushState(null, "/");
}
render() {
return (
<div>
{this.props.children}
<h1>Welcome</h1>
<button onClick={this.navigate.bind(this)}>Featured</button>
</div>
);
}
}
When I click to Link url change, but content is not loaded... Also when I access url I get "Cannot GET" error
After watching the video, you probably want something like this. At first this would not be so easy to understand but after seeing a few of them you digest it. First you render your Layout with one Route. Then in this top route, you use other Routes to setup your components.
We usually use exact props for a top root like /. If you don't setup your app like that, for example all your routes is in your top Router config, then to use a route something like /featured we must have exact prop. If we don't use it Router always hit / path and we always see the top level component.
But, in your situation, you want other components to be routed in your top level component. So, we drop exact prop here.
Also you can use push to change history.
Update
After think about the navigation button named "Featured", I think you want the Featured component rendered as default one here. When hit the button again you will come back to Featured one. I've changed the code according to that. In this version, we add a / route in the Layout and point it to Featured. So, when we come here it is rendered. But, we use exact prop here since we also want routes like "/featured", "/archives" and "/settings".
export default class Layout extends React.Component {
navigate = () => this.props.history.push("/");
render() {
return (
<div>
<h1>Welcome</h1>
<Link to="/featured">Featured</Link>
<Link to="/archives">Archives</Link>
<Link to="/settings">Settings</Link>
<br />
<button onClick={this.navigate}>Featured</button>
<Route exact path="/" component={Featured} />
<Route path="/featured" component={Featured} />
<Route path="/archives" component={Archives} />
<Route path="/settings" component={Settings} />
<div>
Some other info.
</div>
</div>
);
}
}
const app = document.getElementById('root');
ReactDOM.render(
<Router>
<Switch>
<Route path="/" component={Layout} />
</Switch>
</Router>,
app);

react-router-dom Switch needs additional div wrapper

I am using react, react-router-dom and redux to create a simple react application. The package.json file contains:
...
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
...
The project structure is as follow:
- src
- components
- Container
. index.js
+ Customers
+ Greetings
. App.js
- reducers
. customer.js
. index.js
. reducers.js
. Root.js
This is what index.js file looks like:
import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import Root from './Root'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker'
const store = createStore(
rootReducer
)
render(<Root store={ store } />, document.getElementById('root'))
registerServiceWorker()
This is also what is my Root.js file looks like:
import React from 'react'
import PropTypes from 'prop-types'
import { Provider } from 'react-redux'
import { BrowserRouter as Router } from 'react-router-dom';
// Import app component
import App from './components/App'
const Root = ({ store }) => (
<Provider store={ store }>
<Router>
<App />
</Router>
</Provider>
)
Root.propTypes = {
store: PropTypes.object.isRequired
}
export default Root;
And following represents my App component:
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom'
// import pages
import Container from './Container';
import Greetings from './Greetings';
import Customers from './Customers';
class App extends Component {
render() {
return (
<Switch>
<div> // <~~ This is where the issue happens
<Route path="/" component={ Container }></Route>
<Route exact path="/" component={ Greetings }></Route>
<Route path="/customers" component={ Customers }></Route>
</div>
</Switch>
);
}
}
export default App;
The problem is when I use <Switch /> as a wrapper of <Route /> tags, it needs an inner <div /> element, otherwise it will not work.
It means that if I remove the <div /> element inside the <Switch /> and wrap the <Route />s directly by <Switch /> the pages will not be rendered, and also no errors or exception throw in the console.
What is the problem? Am I doing wrong somewhere?
Any help is appreciated.
Edit:
Thanks all for useful comments. Here are some important things to consider:
I don't get any error or warning, react script works fine and compiles my code completely.
As you mentioned, only the first <Route> element of a specific path will be rendered, but when I add a <div> element as first level of <Switch> element as a wrapper for all <Route>s it will work fine. But the problem is I don't need the additional <div> element to be rendered. Please consider that I would like the Container component to be rendered in all pages and other components in same path ('/') should be rendered as children of Container.
There are two solutions:
The solution which Raghav mentioned in comments:
It could be done by making the first <Route /> -which I need to be rendered in all pages- as a container component and use it as a wrapper of other <Route /> inside the <Switch > tag. Gist link from #Raghav
<Switch>
<Container>
<Route exact path="/" component={ Greetings }></Route>
<Route path="/customers" component={ Customers }></Route>
</Container>
</Switch>
The second and a newer solution to this problem is using <React.Fragment> tag which is available in newer versions of React. <React.Fragment> will help you to wrap multiple elements in your component instead of using real html tags.
It will not render any extra elements into page
~~> Link to React documentation for Fragment

React router basic implementation

I am trying to implement React router and I have a class called App from which I want to call ExpenseApp. For ExpenseApp to work, it requires 'data' which I want to pass. Also, my first page of get loaded should be ExpenseApp. As far as I understood react-router, the class name to be specified in the '/' path is the first page to be loaded. The question is how can I pass data from react router to the component.
import React from 'react'
import ReactDOM from 'react-dom'
import {ExpenseApp} from './expense-app.js'
import {Switch, BrowserRouter, Route} from 'react-router-dom'
import {FullBlog} from './FullBlog.js'
var data=[
{
"Author":"Dan Brown",
"Book":"Inferno"
},
{
"Author":"Jeffrey Archer",
"Book":"Be careful what you wish for"
},
{
"Author":"Paulo Coelho",
"Book":"The Alchemist"
}
];
class App extends React.Component{
render(){
return(
<Router>
<Route path='/' component={ExpenseApp}/>
<Route path='fullblog' component={FullBlog}/>
</Router>
)
}
}
ReactDOM.render(<App/>, document.getElementById('container'))
And normally when I was displaying the component without using the react-router, I was doing something like
I am still confused with the concepts of react-router, how can I implement this?
maybe you can try this one :
<Router>
<Route exact path='/' render={() => <ExpenseApp data={data} />}/>
<Route path='fullblog' component={FullBlog}/>
</Router>
this is using react router v4, hope can solve your issue :)
As far as I know, you usually would want to fetch data from within the component, but if it is not possible or you do not want to do this, you could try using decorateComponentWithProps (https://github.com/belle-ui/decorateComponentWithProps)
import decorateComponentWithProps from 'decorate-component-with-props';
// ...
<Route path='/' component={decorateComponentWithProps(ExpenseApp, {data})} />
Given that the ExpenseApp's prop name is data
Edit: As found out in the comments, you also need to change
import {Switch, BrowserRouter, Route} from 'react-router-dom'
to
import {Switch, BrowserRouter as Router, Route} from 'react-router-dom'
For the code to work, or you can also change the usage of <Router /> to <BrowserRouter />

Pagination issue using React Router v4.1

I'm migrating a site in ASP.NET MVC to REACT. And for pagination i have created a component in React.
Issue i'm facing is with Routing for the pagination URLs. React Router is not able to detect that the URL is different when i click on a pagination URL
Let me explain:
app.js code:
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import allReducers from '../reducers/index';
import {Provider} from 'react-redux';
import ReduxPromiseMiddleware from 'redux-promise';
import { BrowserRouter, Route } from 'react-router-dom';
import Main from './main';
import Layout from './layout';
const app = document.getElementById('root');
const store = createStore(allReducers, applyMiddleware(ReduxPromiseMiddleware));
ReactDOM.render(<Provider store={store}>
<BrowserRouter>
<Layout>
<Main/>
</Layout>
</BrowserRouter>
</Provider>
,app);
Main component render:
render(){
return(
<main>
<Switch>
<Route exact path='/' component={HomePage}/>
<Route path='/posts' component={PostsRouter} />
<Route path='/studies' component={StudiesPage} />
</Switch>
</main>
);
}
PostsRouter component:
const PostsRouter = () => (
<Switch>
<Route exact path='/posts' component={PostsPage} />
<Route path='/posts/:page' component={PostsPage} />
</Switch>
);
For both /posts and /posts/2 i need the component to be PostsPage.
Lets say i'm at /home. Now i click a posts link and URL changes to /posts. Now if i click /posts/2 link, nothing happens. React Router doesn't detect that the URL is different.
And a weird thing i noted is that if i change the component:
<Route path='/posts/:page' component={PostsPage} />
to
<Route path='/posts/:page' component={StudiesPage} />
then React Router routes me to StudiesPage component if i click on /posts/2 link when i'm on /posts URL.
May be i'm missing something obvious. But i haven't been able to figure out a way after lots of attempts.
I suspect Sergey's comment was right, that's what my problem ended up being. I was fetching data within componentDidMount() but didn't realise that in order to actually update it with new data when the next page link was clicked, I needed to do the same thing inside componentWillReceiveProps(). You can see my full source here but the biggest key part was this:
componentWillReceiveProps(nextProps) {
this.setState({
loaded: false
});
this.fetchMediaItems(nextProps.match.params.page);
}
componentDidMount() {
this.fetchMediaItems(this.props.match.params.page);
}
componentWillReceiveProps() receives the new properties, including page number, when you click on the link to page 2, so you need to do whatever inside there to update with the new state.

Categories

Resources