Passing props to Parent Component through HOC - javascript

I'm not sure if I'm using a HOC correctly but I have state at the top app level which needs to be updated from a child components that exists in a HOC.
my main app router that holds the state
class AppRouter extends React.Component {
state = {
selected: "",
};
updateSelected = selected => {
this.setState({ selected });
};
updateReports = reports => {
this.setState({ reports });
};
render() {
return (
<Router history={history}>
<div>
<div className="holygrail">
<Header setIsAuth={this.setIsAuth} isAuth={this.state.isAuth} />
<Switch>
<PublicRoute
path="/login"
isAuth={this.state.isAuth}
component={() => <Login setIsAuth={this.setIsAuth} />}
exact={true}
/>
<PrivateRoute
path="/"
selected={this.state.selected}
isAuth={this.state.isAuth}
updateSelected={this.updateSelected}
updateReports={this.updateReports}
component={Dashboard}
exact={true}
/>
<Route component={NotFound} />
</Switch>
</div>
</div>
</Router>
);
}
}
export default AppRouter;
I have a PrivateRoute that then has a template which include a nav that should not be shown on a PublicRoute
export const PrivateRoute = ({ component: Component, isAuth, ...rest }) => (
<Route
{...rest}
render={props => {
console.log("Private Route ", isAuth);
return isAuth ? (
<div className="holygrail-body">
<Nav
updateSelected={this.updateSelected} <-- how to pass these back up to AppRouter parent?
updateReports={this.updateReports}
/>
<Component {...props} />
</div>
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
}}
/>
);
export default PrivateRoute;
How do I pass the Nav props to update the main component state.

Related

React / Redux Authentication Route not redirecting

** Note this is in a react class component
DefaultContainer = () => {
return (
<div className="app_container">
<SideNav />
<TopBar />
<Route exact path="/" component={Home} />
<Route path="/recent" component={Recent} />
<Route path="/AddNote" component={AddNote} />
<Route path="/ToDo" component={ToDo} />
</div>
);
};
// Check for authenticaition
AuthRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (this.props.isAuthenticated) {
return <Component {...props} />;
}
else {
return (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
}
}}
/>
);
};
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={this.LogInContainer} />
<Route exact path="/register" component={this.RegisterContainer} />
<this.AuthRoute component={this.DefaultContainer} />
</Switch>
</BrowserRouter>
);
}
}
I login, this.props.isAuthenticated is set to true. When I try to visit the '/' route I get redirected back to the login? But this.props.isAuthenticated is true in React Dev tools? Cannot grasp what is going wrong.
Should be as simple as this:
AuthRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (props.isAuthenticated) { // <- here is the difference
return <Component {...props} />;
}
else {
return (
<Redirect
to={{
pathname: "/login",
state: { from: props.location }
}}
/>
);
}
}}
/>
);
};

React Conditional rendering doesn't show anything

React app with react-router-dom: 4.3.1:
Main App.js render:
render() {
let routes = (
<Switch>
<Route component={LogIn} path="/login" />
<Redirect to="/login" />
</Switch>
);
if (this.props.isAuthenticated) {
routes = (
<Switch>
<Route component={ParcelListView} path="/" exact />
<Route component={StatusTable} path="/status" />
<Redirect to="/" />
</Switch>
);
}
return (
<div className="app">
{routes}
</div>
);
}
I see white screen When use this code, but when I assign to routes first or second Switch without if it works perfectly in both cases.
I guess the problem comes from assignment in if block. Is this some kind of async thing?
You might want to set routes inside of a <Switch /> component whatever the scenario and have either public or private route components. Here is a common approach:
const PublicRoute = ({
isAuthenticated,
component: Component,
...rest
}) => (
<Route
{...rest}
component={props => (
isAuthenticated ? (
<Redirect to="/somewhere" />
) : (
<Component {...props} />
))}
/>
);
const PrivateRoute = ({
isAuthenticated,
component: Component,
...rest
}) => (
<Route
{...rest}
component={props => (
isAuthenticated ? (
<div>
<Header />
<Component {...props} />
</div>
) : (
<Redirect to="/login" />
)
)}
/>
);
Both components take component (function) and isAuthenticated(boolean) as props and we pass the rest of the props down ({...rest}) anyway (path etc.)
This way you're able to allow/deny routes based on the propspassed down to your components:
...your code
render() {
<Switch>
<PublicRoute path="/" component={YourPublicComponent} />
<PrivateRoute path="/" isAuthenticated component={ParcelListView} />
</Switch>
}
More at Tyler McGinnis's website: https://tylermcginnis.com/react-router-protected-routes-authentication/
Another post on the subject: https://medium.com/#tomlarge/private-routes-with-react-router-dom-28e9f40c7146
You'll be able to find a lot of stuff on the subject on the web

How to correctly handle non PrivateRoutes in React?

I have this piece of code in my app.js and have configured a PrivateRoute which requires the user to login and only allows access if the cookie is set. However, I would like to restrict users trying to hit /login after they have successfully logged in. I used the reverse logic of the PrivateRoute and created LoginRoute which serves the purpose but would like to know if there is a better approach.
import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'
import cookies from 'cookies-js';
import Home from './homeComponent';
import Login from './loginComponent';
import Dashboard from './dashboardComponent';
import NoMatch from './noMatchComponent';
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<LoginRoute path="/login" component={Login} />
<PrivateRoute path="/dashboard" component={Dashboard} />
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
);
};
const LoginRoute = ({ component: Component, rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Redirect to={{
pathname: '/dashboard',
state: { from: props.location }
}} />
: <Component {...props} />
)} />
)
const PrivateRoute = ({ component: Component, rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
)
export default App;
There are a few ways to handle Private Routes, one such way is to write a custom Login route as you have written which prevents user from visiting /login if he/she is already loggedIn. The only correction that you need to make in your route is to use rest syntax correctly
const LoginRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Redirect to={{
pathname: '/dashboard',
state: { from: props.location }
}} />
: <Component {...props} />
)} />
)
and PrivateRoute
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
cookies.get('access-token')
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)} />
)
The other way to handle this would be an authentication HOC.
const RequireAuth = (Component) => {
return class App extends Component {
render() {
const { location } = this.props;
if (cookies.get('access-token')) {
if(location.pathname === '/login') {
return <Redirect to={'/dashboard'} />
}
return <Component {...this.props} />
}
return <Redirect to="/login"/>
}
}
}
export { RequireAuth }
and you would use it like
const App = ({ history }) => {
return (
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/login" component={RequireAuth(Login)} />
<Route path="/dashboard" component={RequireAuth(Dashboard)} />
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
);
};

Why this pass props into this.props.children doesn't work?

I tried to pass in props to this.props.children using the following code
export default class Home extends Component {
render(){
var children = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
foo: "1"
})
});
return(
<div className="bla">
<h1>WeDate</h1>
<div className="child">
{children}
</div>)
}
}
But I can't read this.props.foo in my searchDate component when it renders normally.
The following is my react router.
render(
<Router>
<Home>
<Switch>
<Route exact path="/"><Redirect to="/search" push/></Route>
<Route exact path="/search" component={SearchDate}></Route>
</Switch>
</Home>
</Router>
,document.getElementById('app')
);
the children to your Home component are not the Routes but the Switch and hence foo is not passed down as props to the respective components. What you need to do is to nest your Routes is the Home component and not as children
Home
export default class Home extends Component {
render(){
return(
<div className="bla">
<h1>WeDate</h1>
<div className="child">
<Switch>
<Redirect from="/" exact to="/search"/>
<Route exact path="/search" render={(props) => <SearchDate foo={'1'} {...props}/>}>
</Switch>
</div>)
}
}
Routes
render(
<Router>
<Home />
</Router>
,document.getElementById('app')
);

multiple page in react router v4

I am using react router v4 for routing. The layout my app is, there is homepage which is for end user. The path for homepage is obviously /. There is dashboard section too. One for admin, one for agent and another for owner. They have their own layout from top to bottom. For homepage its working. But when i hit url /admin/dashboard, the main page of admin dasboard is not shown. The same homepage is shown.
Here is what i have done
const AsyncRoute = ({ load, ...others }) => (
<Route
{...others} render={(props) => (
<Bundle load={load} {...props} />
)}
/>
);
app.js
const render = messages => {
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById("app")
);
};
import Routes from 'routes';
class App extends React.Component {
render() {
return (
<div>
<Navbar userForm={this.handleDialog} />
<Routes />
</div>
);
}
}
routes.js
function Routes({ location }) {
return (
<Switch location={location}>
<AsyncRoute exact path="/" load={loadHomePage} />
<AsyncRoute exact path="/features" load={loadFeaturePage} />
<AsyncRoute path="" load={loadNotFoundPage} />
</Switch>
);
}
I want now admin dashboard a complete new page with different layout not children of App component so i did
the following
class AdminDashboard extends React.Component {
render() {
return (
<div>
<TopNavigation />
<SideNavigation />{/* it will have link */}
<Routes /> {/* it will display page */}
</div>
);
}
}
function AdminRoutes({ location }) {
return (
<Switch location={location}>
<AsyncRoute
exact
path="/admin/dashboard"
load={loadAdminDashboardPage}
/>
<AsyncRoute exact path="/commission" load={loadCommissionPage} />
<AsyncRoute path="" load={loadNotFoundPage} />
</Switch>
);
}
when i hit the url /admin/dashboard i get the app page not the admin dashboard page and same with the
/commission which should be a child of AdminDashboard
How can i make my router work for different layout?
From Meteorchef Base, dedicated routing according to the user (loggingIn prop in this case):
Public.js, only for non admin, redirect if not :
import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
const Public = ({ loggingIn, authenticated, component, ...rest }) => (
<Route {...rest} render={(props) => {
if (loggingIn) return <div></div>;
return !authenticated ?
(React.createElement(component, { ...props, loggingIn, authenticated })) :
(<Redirect to="/account" />);
}} />
);
Public.propTypes = {
loggingIn: PropTypes.bool,
authenticated: PropTypes.bool,
component: PropTypes.func,
};
export default Public;
Authenticated.js, only for admin, also redirect if not :
import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
const Authenticated = ({ loggingIn, authenticated, component, ...rest }) => (
<Route {...rest} render={(props) => {
if (loggingIn) return <div></div>;
return authenticated ?
(React.createElement(component, { ...props, loggingIn, authenticated })) :
(<Redirect to="/login" />);
}} />
);
Authenticated.propTypes = {
loggingIn: PropTypes.bool,
authenticated: PropTypes.bool,
component: PropTypes.func,
};
export default Authenticated;
then in your App, (stateless in this case, but you can create a class as well too) :
// import everything
const App = appProps => (
<Router>
<div>
<Switch>
<Route exact name="index" path="/" component={Home} />
<Authenticated exact path="/account" component={Account} {...appProps} />
<Public path="/signup" component={Signup} {...appProps} />
<Public path="/login" component={Login} {...appProps} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
);
App.propTypes = {
loggingIn: PropTypes.bool,
authenticated: PropTypes.bool,
};

Categories