react-router v4 - browserHistory is undefined - javascript

I am creating my first react app in electron (my first electron app too). I have two routes & need to navigate from one to another. For that I am using following code:
Root
ReactDOM.render(
<Router history={browserHistory}>
<App />
</Router>,
document.getElementById('root')
);
App
class App extends React.Component {
constructor() {
super();
}
render() {
return (
<div className="app-master">
<Switch>
<Route path='/city' component={CityList}/>
<Route path='/' component={SplashScreen}/>
</Switch>
</div>
)
}
}
Page
import { browserHistory } from 'react-router';
...
browserHistory.push('/city');
This line gives error,
TypeError: Cannot read property 'push' of undefined
I searched web for possible solution but can't find one! There are many similar questions on SO too, but none of it worked for me :(

You have to import it from the history module now which provides 3 different methods to create different histories.
createBrowserHistory is for use in modern web browsers that support the history API
createMemoryHistory is used as a reference implementation and may also be used in non-DOM environments, like React Native or tests
createHashHistory for legacy web browsers
You cannot use the browser history in an electron environment, use the hash or the memory one.
import { createHashHistory } from 'history'
const history = createHashHistory()
You can then use the history injected in the props
this.props.history.push('/')

Useful pointers above. The simplest solution I've found is to add:
import {createBrowserHistory} from 'history';
to your list of import statements, then add:
const browserHistory = createBrowserHistory();
Might not work perfectly, but for the basic stuff I'm working on seems to do the trick. Hope that helps.

Its is not working for your because in your component you are still using browserHistory which is not longer availabe from react-router package. You should change to using history from the history package
To simplify you can create a history.js file with the following contents
import { createBrowserHistory } from 'history'
export default createBrowserHistory();
Root
import history from '/path/to/history';
ReactDOM.render(
<Router history={history}>
<App />
</Router>,
document.getElementById('root')
);
Page
import history from 'path/to/history';
...
history.push('/city');

import { browserHistory } from 'react-router' does not work in React router 4. Link
Use the redirect component:
import { Redirect } from 'react-router';
<Redirect push to="/somewhere/else"/>
The render function should replace the entire content with Redirect component.

In react-router v4 initialize router as constant config and access the history through this.props in child components.
Import you dependecies
import { Route, Router } from "react-router";
import { createBrowserHistory } from "history";
Define your router config and add history as prop
const history = createBrowserHistory();
const routes = (
<Router history={history}>
<Route path='/city' component={CityList}/>
<Route path='/' component={SplashScreen}/>
</Router> )
class App extends Component {
render() {
return (
<div className = "app-master>
{routes}
</div>)
}
Defining route as a constant and out of render method this would initialize the route config only once.
Page Component
class Page extend Component {
render() {
this.props.history.push('/');
}
}
The history is now available as props in all the child components defined in routes config.

Related

React-router , router not workingg

I'm newbie in reactjs, I tried build something with it but I had problem with react-router-redux. I get React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. in console. Here is my code :
App.js
import React, { PropTypes } from 'react';
class App extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default App;
Routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router'
import App from './components/App';
import Login from './components/login/Login';
import Register from './components/register/Register';
export default (
<Route path="/" component={App}>
<IndexRoute component={Login}/>
<Route path="register" component={Register}/>
</Route>
);
And Index.js
...
import { syncHistoryWithStore } from 'react-router-redux'
import { Router } from 'react-router'
import { createBrowserHistory } from 'history';
import routes from './routes';
const store = configureStore();
const history = syncHistoryWithStore(createBrowserHistory(), store)
ReactDOM.render(
<Provider store={store}>
<Router history={history} routes={routes}>
</Router>
</Provider>,
document.getElementById('app')
);
Where is my wrong? Please explain for me why I get this error. Thank in advance
React-router-redux is no longer maintained and support only 3.x and 2.x React-router versions
Repo authors suggest using connected-react-router for React-rotuer 4.x bindings
There are different routers for different environments, you want to use BrowserRouter instead of Router.
See React Training BrowserRouter for more information.
index.js
// change this line
import { Router } from 'react-router';
// to
import { BrowserRouter as Router } from 'react-router-dom';
NOTE: You might also have to pass in your routes in a different way. This is shown in the React Training page provided above.

State and routing for imported React components

I have to write an integrated chat module that has two versions - a small in-site window (like facebook messenger) and full version that is opened in a new tab (a new react-router route). So, this module exports two components: <ChatWindow /> and <ChatFullView />for these views respectively.
// core application
import {ChatWindow, ChatFullView} from 'chat-module';
// <PageContentWithChat /> contains imported <ChatWindow />
<Switch>
<Route path='/' component={PageContentWithChat} />
<Route path='/fullview' component={ChatFullView} />
</Switch>
So, the question is:
Where should I declare the redux store and manage it for both of them? (They must have one united store because the messages from the window version should be rendered in full view and vice versa)
EDIT:
I wanted to control the module from the inside:
// in module
const store = createStore(reducer);
....
<Provider store={store}>
<ChatWindow />
<ChatFullView />
</Provider>
But I'm afraid I won't be able to export these components separately as they are wrapped with <Provider />. How is it possible to solve this?
react-redux makes the store available through context via the Provider component.
Assuming <ChatWindow /> and <ChatFullView /> are connected components, you would wrap everything in <Provider />, passing in your store as a prop.
Of course, you can organize all of this into different files, but this is the general idea.
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Switch, Route } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { createStore } from 'redux';
import PageContentWithChat from 'path-to-page-content-with-chat';
import { ChatWindow, ChatFullView } from 'chat-module';
const store = createStore(/* reducers + initial message state passed in here... */);
const container = document.getElementById(/* id of your app container */);
const component = (
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route path='/' component={PageContentWithChat} />
<Route path='/fullview' component={ChatFullView} />
</Switch>
</BrowserRouter>
</Provider>
);
render(component, container);

Images don't show only when optional html parameter is provided (but do show otherwise)

I have parent component that shows an image at a specified path (note: the image is already saved in my project). This path optionally can have additional parameters. If the
For example, The image is displayed (image) if the html path is:
www.mysite.com/myPath
The component is displayed but image is broken (broken image) if the html path is:
www.mysite.com/myPath/someFilterForThisPage
Router
// Libraries
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { browserHistory } from 'react-router';
// Components
import Home from './containers/Home';
import NotFound from './components/NotFound';
import MyComponent from './components/MyComponent';
// Redux
import { Provider } from 'react-redux';
import {createStore} from 'redux';
import allReducers from './reducers';
const store = createStore(
allReducers,
window.devToolsExtension && window.devToolsExtension()
);
// Routes
const routes = (
<Router history={browserHistory}>
<div>
<Provider store={store}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/myPath/:filter?" component={MyComponent} />
<Route component={NotFound} />
</Switch>
</Provider>
</div>
</Router>
);
export default routes;
I don't think the issue is with my router.js file since the component still shows when a filter is applied in the html path (the image is just broken, ), but I am providing it just in case I am misunderstanding something.
My Component:
// React
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
<div>
<img src={"img/x.png"} id="someId" alt=""/> // ISSUE
// ...
// some divs that show/don't based on the filter of the html path
// ...
</div>
}
}
export default MyComponent;
I have looked at and tried some of the following, but with little luck:
React won't load local images
Dynamically Add Images React Webpack
I think these are different because these are mainly issues related to being unable to display images at all. I am able to display the image, but only when the optional html parameter is not set.
Does anyone know why the image is showing, but only if there is no extra html parameter?
Many thanks.
Any reason why {"img/x.png"} is not accessing root? Such as {"/img/x.png"} or setup your env domain as a global variable and add that in there otherwise you are looking inside every directory you hit for an img directory.

reactjs - can not read property push of undefined

I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?
route.js
import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory, IndexRoute } from "react-router";
import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";
const app = document.getElementById('app');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Features} />
<Route path="archive" component={Archive} />
</Route>
</Router>, app);
Layout component
import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
navigate(){
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}
package.json - partial
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
"history": "^2.0.1",
-------------update to jordan's answer-------------
In React Router v4, you no longer have to give a history to your router. Instead you just use BrowserRouter or HashRouter from 'react-router-dom'. But that makes it unclear how to push a rout to your history when you aren't in a react component.
The solution is to use the history package.
Just import createHistory like this:
import createHistory from 'history/createBrowserHistory'
Or the way I do it is like this:
import { createHashHistory } from 'history'
then create your history
export const history = createHashHistory()
and now you can push to it:
history.push('/page')
I hope this helps others who come to this question. None of the current answers gave me what I needed.
This may not be referring to above example but I had the same error. After lot of debugging I figured out that history is not reachable to my inner components. Make sure your history is reachable.
//main.js
<BrowserRouter>
<div>
<Route path="/" component={Home}/>
<Route path="/techMap" component={TechMap}/>
</div>
</BrowserRouter>
//app.js
<div>
<TechStack history= {this.props.history}/>
</div>
//techstack.js
<div>
<span onClick={this.search.bind(this)}>
</span>
</div>
)
search(e){
this.props.history.push('/some_url');
}
TechStack is my inner component.
Earlier I was able to get history in app.js but not in tech.js.
But after passing props in form of history, I got the history in tech.js and routing works
With React router v4, you need to wrap the components in withRouter. Then you can access history in your components. Do the following:
import { withRouter } from 'react-router-dom';
...
...
export default withRouter(MyComponent);
You need to change your route.js page to
import {Router, browserHistory} from 'react-router';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Features} />
<Route path="archive" component={Archive} />
</Route>
</Router>, app);
And then everywhere you want to navigate you can use
import {Router, browserHistory} from 'react-router';
browserHistory.push('/');
The react-router docs encourage you to use browserHistory instead of hashHistory
hashHistory uses URL hashes, along with a query key to keep track of
state. hashHistory requires no additional server configuration, but is
generally less preferred than browserHistory.
usually, when you are trying to redirect from a nested component it will give this error.
there are a few ways to fix it
Using react-dom you can import the withRouter component from react-router-dom then use it as usual with this.props.history.push and instead of the usual export default 'class' we will use export default withRouter(class); and boom problem solve.
I use browserHistory instead of HashHistory.
Then I just need to do the following:
import { browserHistory } from 'react-router'
// ...
// ...
navigate(){
browserHistory.push('/');
}
You don't need to use browserHistory anymore.
React-router-dom inject into your component route related props and context.
One of this props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.
example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link
redirectToPage() {
this.props.history.push('/page'); OR
this.context.router.history.push('/page');
}
while in a function base stateless component
redirectToSessionStatePage() {
props.history.push('/page');OR
context.router.history.push('/page');
}
Change your Layout component to have navigate assigned to ES6 lambda. This is needed to set the correct value of this
import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
navigate = () => {
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}
export default class Layout extends React.Component{
navigate = () => {
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}
Layout.contextTypes = {
router: PropTypes.object.isRequired
}
It looks like you overwrote your Features import with whatever is in your /archives directory. In the code you posted, you have this:
import Features from "./page/Features";
import Features from "./page/archive";
import {withRouter} from 'react-router-dom';
export default withRouter(AppName);

How can I navigate outside of components in react-router-1.0.3 in React's render()?

I want to route to another path in the render function in react-router-1.0.3. I can redirect the user by providing a link using:
render(
<Link to={`/${this.props.params.projectSlug}/`}>
Please follow this link to access your workspace.
</Link>
)
But I cant seem to programmatically forward to this link. I tried:
render(
<Router history={browserHistory} routes=
{`/${this.props.params.projectSlug}/`}/>
)
How can I programmatically forward to a relative path in react-router 1.0.3?
Try upgrade router to the latest version if you don't mind;
Then, they strictly clarify how to do it here.
// Your main file that renders a <Router>:
import { Router, browserHistory } from 'react-router'
import routes from './app/routes'
render(
<Router history={browserHistory} routes={routes} />,
mountNode
)
&
// Somewhere like a Redux middleware or Flux action:
import { browserHistory } from 'react-router'
// Go to /some/path.
browserHistory.push('/some/path')
// Go back to previous location.
browserHistory.goBack()

Categories