this.props.history.push not working - reactjs

When i export a component like:
export default class Link extends React.Component{
onLogout() {
this.props.history.push('/');
}
the button that this is tied to correctly changes the page in react-router v4.
However, in my main.js file, I am currently trying to get something like:
if (insert conditional here) {
this.props.history.push('/');
}
to work. But it just give me a type error.
'Uncaught TypeError: Cannot read property 'history' of undefined'.
I do have all the correct dependencies installed, and it works just fine in my other component. I'm currently having this if statement in the main js file (its a small project im practicing to understand v4), so I'm thinking it might be because I'm not extending a class.
Does anyone have any idea why the same code wouldn't be working in the main file, and is there a workaround for this? All the react-router v4 changes are befuddling this rookie.

This means that this.props is not defined, because you are using this.props in a callback where this is not what you think it is. To solve this, use your callback like this:
<button onClick={this.onLogout.bind(this)}>
instead of
<button onClick={this.onLogout}>
You can also do
import { browserHistory } from 'react-router'
... browserHistory.push('/');
Edit: Regarding the latter, you can also wrap your component with this:
import { withRouter } from 'react-router';
// in YourComponent:
... this.props.router.push('/');
export default withRouter(YourComponent);
It may be better than browserHistory because you don't have to specify the history type (could be changed to hashHistory and still work).

I would suggest you to not a address directly into the history but use .
You can send the user to the page and you can conditionally check if he is allowed to see the content if yes then render in render method return the component else return
This would result in a cleaner code.
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md

Related

react redux: private route not rendering layout

Code Sandbox link:
and trying to follow this article
On successful login(/auth/login), the user should be routed to the dashboard(/admin/summary). If the login is successful, I am also storing an access token.
I have a PrivateRoute component for this. The problem is that on successful login, the URL is getting updated but the component is not getting rendered.
PS: about the dashboard, this is a single page application so, the dashboard has topbar, sidebar, and the right content and altogether these things are coupled inside <AdminLayout/>. So, in my AppRouter, I have to render the <AdminLayout/> and just any one component.
All the react and redux code is included in the code sandbox.
Since in your code you create your own history object (it happens in you history.js file, when you call createBrowserHistory()) but doesn't pass it to your Router, nothing happens.
There are 2 possible solutions:
1. Don't create a history object yourself, but use useHistory hook inside your component
Working Demo
With this approach, you should remove history.push from login.actions.js (which imports history) and use history.push in Login.js (which uses useHistory hook):
// login.actions.js
...
loginService.login(userid, password, rememberPassword).then(
(userid) => {
dispatch(success(userid, password, rememberPassword));
// history.push(from); <-- commented out!
},
(error) => { ... }
);
};
...
// Login.js
function handleSubmit(e) {
...
const { from } = {
from: { pathname: "/admin/summary" }
};
history.push(from) // <-- added!
dispatch(loginActions.login(inputs, from));
...
}
useHistory exposes the history object of BrowserRouter (I think this is implied in this official blog post).
2. Create a history object yourself, but pass it to a Router component
Working Demo
This approach would require you to make several changes:
Creating the history object on your own means you become responsible to provide it to a router component, but it can't be a BrowserRouter, but the base Router component (see these Github answers: 1, 2).
Once you import Router (instead of BrowserRouter), you need to get rid of any useLocation and useHistory imports, otherwise you'll get errors.
I also had to unify the history object export and imports, so that it is exported as the default export (i.e., export default history), and it is imported as the default import (i.e., import history from "./history"; instead of import { history } from "./history")
(P.S: this approach can be seen implemented elsewhere on SO, for example here or here (the latter explicitly installs history, but it's not needed in your case).

React redirect on click of svg element

I have a single page React App that is d3 and SVG heavy, and I would like to be able to redirect from one page to another when a user clicks on an svg rect on one of my pages. I am familiar with this.props.history.push() as well as the <Link> component from the react-router-dom library, however neither of these seem to help in this instance.
The svg element of relevance here is deep in a graphing component of mine that is 3-4 children down from the front-end's main App.js file that does all of the routing, and when I run console.log(this.props) in my component with the svg, there is no history object on the props. I'm not sure if a reproducible example is needed here, as I just need direction.
In short, I have no idea what should go into the on-click function that is associated with my svg rect, to enable redirect in my app. Any thoughts on this would be greatly appreciated!
Edit: obviously this is wrong but i tried to return a Redirect component in on-click handler and it didn't work:
...
...
function handleMouseClick() {
console.log('clicked')
return <Redirect to='/stats' />;
}
myRect.on('click', handleMouseClick)
...
Edit2: should i put the rect elements inside of components in the svg? is that even possible?
You can add the history prop from react-router to a component by wrapping it with withRouter. Just make sure whatever is mounting your component is using the wrapped version (usually by only exporting the wrapped component).
import React from 'react';
import { withRouter } from 'react-router';
class MyComponent extends React.Component {
render() {
return (
<button onClick={() => this.props.history.push('/newpage')}>
Click me
</button>
);
}
}
export default withRouter(MyComponent);

Can you go backwards through react-router v4 hashHistory?

Wondering how to go back to a previous route in a react web app using hashRouter instead of browserRouter in react-router v4?
I've found this question which doesn't seem to work even though it says no browser mixin needed (plus I think its talking about an older react-router version) however, every other solution I've seen depends on browserHistory.
Is it possible with hashHistory?
this.props.history.goBack()
Taken from the comments on this question
It is a function call.
Well in my case i did like that :
import withRouter from "react-router-dom/es/withRouter";
import React from "react";
class Component extends React.Component {
goBack() {
this.props.history.go(-1);
}
...
}
const WrappedComponent = withRouter(Component)
export default WrappedComponent;
withRouter give us access to history in props of component, but i'm not sure is this way is correct

Please explain this abbreviated ES6 JSX declaration

An example in the SurviveJS handbook in the chapter on React and Webpack has me confused.
In Note.jsx:
import React from 'react';
export default () => <div>Learn Webpack</div>;
This deviates in a number of ways from what appears to be the standard way of declaring React components using JSX:
import React from 'react';
class Note extends React.Component {
render() {
return <div>Learn Webpack</div>;
}
}
How does the first example work?
How does it know the component is called Note so that it can be referred to as <Note/> in some parent component? Simply by filename match (removing the .jsx part?)
Where's the render() function? And how is it possible to omit it?
What are the limitations of this approach? I am guessing that it only works for wrapping a very simple rendered output, just mapping properties into some HTML...
Where is this style documented? I can't seem to find any official documentation
It doesn't, when you do <Note /> that is just looking for a variable named Note in the local scope. When the component is imported into another file, you can name it whatever you want. e.g. import Note from './Note'; would import the default-exported function in your example.
This is a stateless function component, https://facebook.github.io/react/docs/reusable-components.html#stateless-functions, as you linked to yourself. The function itself is the render, it has no class instance.
They can store no state since they just take inputs and render outputs.
Your specific example is just an arrow function. The documentation linked above uses standard non-arrow functions, but they are essentially interchangable in this case. e.g.
export default () => <div>Learn Webpack</div>;
is the same as
export default function(){
return <div>Learn Webpack</div>;
}

How to render a reactjs component stored in a redux reducer?

I have a redux reducer loaded with several reactjs components.
I want to load these inside other components through this.props
Like: this.props.components.MyReactComponent
class OtherComponent extends Component {
render() {
const Component = this.props.components.MyReactComponent
return (
<div>
<Component />
</div>
)
}
}
Is this possible? If so, how?
EDIT The component is a connected component. I am able to load it but it is broken. In this case, it is a counter, when you click to increment or decrement nothing happens. In the console, there is this error:
Uncaught ReferenceError: _classCallCheck is not defined
if I convert the component into a dumb component (without connecting it), the error is this:
Uncaught ReferenceError: _classCallCheck3 is not defined
EDIT 2
I found out why those errors show up. It is because the react component gets stripped out when stored in the reducer:
A react component would look something like this:
{ function:
{ [Function: Connect]
displayName: 'Connect(Counter)',
WrappedComponent: { [Function: Counter] propTypes: [Object] },
contextTypes: { store: [Object] },
propTypes: { store: [Object] } } }
However, after I store it inside a reducer, it loses its properties and ends up looking something like this:
{ function:
{ [Function: Connect] } }
After reading the comments below, I thought of an alternative. I can store in a reducer the path to each component, then make a new wrapper component that could render those other components from those paths.
I tried it but encoutered a different problem with the funcion require from nodejs that for some weird reason is not letting me user a variable as an argument. For example:
This works:
var SomeContent = require('../extensions/myContent/containers')
This does not:
var testpath = '../extensions/myContent/containers'
var SomeContent = require(testpath)
Giving me the following error:
Uncaught Error: Cannot find module '../extensions/myContent/containers'.
It is adding a period at the end of the path. How can I prevent require to add that period?
If you can think of any other alternative I can implement for what I am trying to do, I would greatly appreciate it.
EDIT 3 Following Thomas advice...
What I am trying to accomplish is this:
I want to be able to render react components inside other react components, I know how to do it the same way most us know how to; however, I want to be able to do it by importing a file that would contain all the components without actually having to import and export each one of them:
OtherComponent.js
import React, { Component } from 'react'
import { SomeComponent } from '../allComponentes/index.js'
export default class OtherComponent extends Component {
render() {
return (
<SomeComponent />
)
}
}
SomeComponent.js
import React, { Component } from 'react'
export default class SomeComponent extends Component {
render() {
return (
<div>
Hello
</div>
)
}
}
allComponents/index.js
import SomeComponent from '../allComponents/SomeComponent/index.js'
export { SomeComponent }
What I am trying to do in allComponents/index.js is to avoid having import/export statements for each component by reading (with fs module) all the components inside the allComponents folder and export them.
allComponents/index.js (pseudocode)
get all folders inside allComponents folder
loop through each folder and require the components
store each component inside an object
export object
When I tried that, I encountered multiple issues, for one, export statements have to be in the top-level, and second, fs would work only on the server side.
So, that is why I thought of loading all the components in a reducer and then pass them as props. But as I found out, they got stripped out when stored them in a reducer.
Then, I thought of only storing the path to those components inside a reducer and have a wrapper component that would use that path to require the needed component. This method almost worked out but the nodejs function require wont allow me to pass a variable as an argument (as shown in EDIT 2)
I think your question is not really to do with redux but rather is (as you say):
What I am trying to do in allComponents/index.js is to avoid having import/export statements for each component by reading (with fs module) all the components inside the allComponents folder and export them.
By way of example, I have all of my (dumb) form components in a folder path components/form-components and the index.js looks something like:
export FieldSet from './FieldSet'
export Input from './Input'
export Label from './Label'
export Submit from './Submit'
export Select from './Select'
export Textarea from './Textarea'
Then when I want to import a component elsewhere, it is import { FieldSet, Label, Input, Submit } from '../../components/form-components/';

Resources