Here I want that only loggedin user should be able to open the profile route. What is the best way to do it?
main.js
let store = createStore(todoApp, applyMiddleware(thunkMiddleware));
render(
<Provider store={store}>
<Router history={browserHistory}>
<div className="container">
<Route exact path="/" component={Login}/>
<Route path="/profile" component={Profile} />
</div>
</Router>
</Provider>,
document.getElementById('root')
)
You could do somthing like :
<Route path="/profile" component={RequiresAuth(Profile)} />
And create a authentication function like :
function RequiresAuth(ComposedComponent) {
class Authenticate extends Component {
render() {
if (!userAuthenticated) { // Check if user is authenticated
return null;
} else {
return (
<ComposedComponent {...this.props} />
);
}
}
}
}
Related
I am using react-router-dom v6, "react": "^18.2.0", and not able to render a Details component. This is my routing:
function Routing() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<List />} />
<Route path="details/:id" element={<Details />} />
<Route path="other" element={<Other />} />
</Routes>
</BrowserRouter>
);
}
I am using this to try to access the Details component:
<Link to={'details' + `/${props.id}`}/>
The details component is as basic as this:
import react from 'React'
const Details = () => {
return (<h1>HELLO</h1>)
}
export default Details;
But the component will not render, and I am getting the warning "No routes matched location "/details/weI4qFO9/UW9v5WFllYhFw==""
It's only dynamic routing that will not render the component. Any idea what I am doing wrong or missing?
you are missing the / before details on the router and the link
function Routing() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<List />} />
<Route path="/details/:id" element={<Details />} />
<Route path="/other" element={<Other />} />
</Routes>
</BrowserRouter>
);
}
<Link to={`/details/${props.id}`}/>
I'm having some kind of trouble when I'm using Router in App.js
I'm getting a blank page when I am using, I tried a lot but couldn't found a way to solve the issue.
<GuestRoute path="/Authenticate" element={<Authenticate />}>
</GuestRoute>
it is working fine with
<Route path="/Authenticate" element={<Authenticate />}>
</Route>
but I have to use GuestRoute.
Given below is the whole code:
App.js
import "./App.css";
import {BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import React from "react"
import Navigation from "./components/shared/Navigation/Navigation";
import Home from "./Pages/Home/Home";
import Register from "./Pages/Register/Register";
import Login from "./Pages/Login/Login";
import Authenticate from "./Pages/Authenticate/Authenticate";
const isAuth = true;
function App() {
return (
<div className="App">
<Router>
<Navigation />
{/* switch(prev. versions) ----> Routes (new versions)) */}
<Routes>
<Route exact path="/" element={<Home />} >
</Route>
<GuestRoute path="/Authenticate" element={<Authenticate />}>
</GuestRoute>
</Routes>
</Router>
</div>
);
}
const GuestRoute = ({children,...rest}) => {
return(
<Route {...rest}
render={({location})=>{
return isAuth ? (
<Navigate to={{
pathname: '/rooms',
state: {from: location}
}}
/>
):(
children
);
}}
></Route>
);
};
export default App;
react-router-dom#6 doesn't use custom route components. The new pattern used in v6 are either wrapper components or layout route components.
Wrapper component example:
const GuestWrapper = ({ children }) => {
... guest route wrapper logic ...
return (
...
{children}
...
);
};
...
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/Authenticate"
element={(
<GuestWrapper>
<Authenticate />
</GuestWrapper>
)}
/>
</Routes>
</Router>
Layout route component example:
import { Outlet } from 'react-router-dom';
const GuestLayout = () => {
... guest route wrapper logic ...
return (
...
<Outlet /> // <-- nested routes render here
...
);
};
...
<Router>
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route element={<GuestLayout>}>
<Route path="/Authenticate" element={<Authenticate />} />
... other GuestRoute routes ...
</Route>
</Routes>
</Router>
When changing the screen, using history.push the new screen is not loaded.
I've seen some posts about it, but no solution has actually helped.
ReactDOM.render(
<Router history={history}>
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
</Router>,
document.getElementById('root')
);
Above is my main component, where I use redux
const isLogged = localStorage.getItem('user')
const PrivateRoute = (props) => {
return isLogged ? <Route {...props} /> : <Redirect to="/login" />
}
const App = () => {
return (
<MuiThemeProvider theme={theme}>
<div className="container-fluid p-0" style={{ backgroundColor: 'rgba(0,0,0,0.2)', }}>
<Switch>
<Route exact path='/login' component={Login} />
<PrivateRoute exact path="/" component={Dashboard} />
</Switch>
<AlertComponent />
</div>
</MuiThemeProvider>
);
}
Here is my component of routes where I have the login screen and the main screen of my application.
const authenticate = () => {
setLoading(true)
UserService.login(email, password, (response) => {
setLoading(false)
response.error ?
dispatch(createAlertError('Email e/ou senha inválida'))
:
dispatch(userSignInSuccess(response.user.shift()))
history.push('/')
})
}
Here in my login component, when calling this function the route changes, but the new component is not updated.
Here is the repository link
There are some issues in your code which you can correct
In your main component don't wrap Provider with <Router>, wrap in <Provider />, in that way route handlers can get access to the store. To know more click
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
In your App.js use <Router> and no need to inject history object there, when you're using react router, connected component will have access to it.
Like the <PrivateRoute> create one more component as <PublicRoute> which will do the exact opposite check of <PrivateRoute>
const isLogged = localStorage.getItem('user')
const PrivateRoute = (props) => {
return isLogged ? <Route {...props} /> : <Redirect to="/login" />
}
const App = () => {
return (
<MuiThemeProvider theme={theme}>
<div className="container-fluid p-0" style={{ backgroundColor: 'rgba(0,0,0,0.2)', }}>
<Router>
<Switch>
<Route exact path='/login' component={Login} />
<PrivateRoute exact path="/" component={Dashboard} />
</Switch>
</Router>
<AlertComponent />
</div>
</MuiThemeProvider>
);
}
Try above steps and let me know your progress, Thanks
const authenticate = () => {
setLoading(true)
UserService.login(email, password, (response) => {
setLoading(false)
response.error ?
dispatch(createAlertError('Email e/ou senha inválida'))
:
dispatch(userSignInSuccess(response.user.shift()), history.push('/'), history.go(0))
})
}
history.go(0) to render the page again
I have a simple React app and I'm trying to implement auth logic. This is how my application looks like:
class App extends Component {
render() {
return (
<Router history={history}>
<div className="App">
<Switch>
<PrivateRoute path="/account" component={Account} />
<Route component={PublicLayout} />
</Switch>
</div>
</Router>
)
}
}
My auth logic is: if user isAuthenticated === true render /account page else redirect to /signin. So for this I created my own simple PrivateRoute functional component:
export default ({ component: Component, ...args }) => {
return (
<div>
<Route {...args} render={(props) => {
return fakeAuth.isAuthenticated === true
? <Component {...props} />
: <Redirect to='/signin' />
}} />
</div>
)
}
Because PrivateRoute path="/account" is NOT exact path I expect that if user goes to /account-setting it will redirect him to /sign-in. But it's not working. The user successfully goes to /account-setting and see PublicLayout.
Why is that? There is no exact key in route, it has to grab all that starts from "/account" and use my logic in the PrivateRoute functional component.
Not providing exact props doesn't mean that it will match /account, /account-settings but it will match /account, /account/other, /account/other/paths. So, you'll need to provide both path:
<PrivateRoute path="/account" component={Account} />
<PrivateRoute path="/account-setting" component={Account} />
Or, you may use regex:
<PrivateRoute path="/account(?=\S*)([a-zA-Z-]+)" component={Account} />
New to react & react-router.
I'm trying to understand this example:
https://github.com/ReactTraining/react-router/blob/1.0.x/docs/API.md#components-1
But this.props never contains main or sidebar. My code:
Main.js
ReactDOM.render(
<Router>
<Route path="/" component={App2}>
<Route path="/" components={{main: Home, sidebar: HomeSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
App2.js
class App2 extends React.Component {
render() {
const {main, sidebar} = this.props;
return (
<div>
<Menu inverted vertical fixed="left">
{sidebar}
</Menu>
<Container className="main-container">
{main}
</Container>
</div>
);
}
}
export default App2;
Home.js
import React from 'react';
class Home extends React.Component {
render() {
return (
<div><h1>Home</h1></div>
);
}
}
export default Home;
HomeSidebar.js
class HomeSidebar extends React.Component {
render() {
return (
<div>
<p>I'm a sidebar</p>
</div>
);
}
}
export default HomeSidebar;
I'm using electron with react dev tools. Whenever I debug, this.props contains neither main nor sidebar. Any idea why this is happening?
I've also tried using an IndexRoute, but it seems to not support a components prop.
Other things I've tried
ReactDOM.render(
<Router>
<Route component={App2}>
<Route path="/" components={{main: Home, sidebar: HomeSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
ReactDOM.render(
<Router>
<Route path="/" component={App2} components={{main: Home, sidebar: HomeSidebar}}>
<Route path="admin" components={{main: Admin, sidebar: AdminSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
Looks like to have the components prop work you need use the <IndexRoute /> component instead of <Route />. In the react-router docs it mentions that IndexRoute has all of the same props as Route so doing
<IndexRoute components={{main: Main, side: Side}} />
works!
Full code:
React.render((
<Router>
<Route path="/" component={App} >
<IndexRoute components={{main: Main, side: Side}} />
</Route>
</Router>
), document.getElementById('app'))
Codepen: http://codepen.io/chmaltsp/pen/ZeLaPr?editors=001
Cheers!
If you're using the current version of react-router (v4.0.0), it looks like they did away with the components prop on Routes: https://reacttraining.com/react-router/web/api/Route
You can render Routes anywhere, and they even have a sidebar example where they do just that. They have one set of Route components to render the main components and another set of Route components for sidebars, but both come from a single route config to keep it DRY.
To translate that to your code, you could create a route config:
const routes = [
{ path: '/',
sidebar: Sidebar
main: Main
}
];
Then in Main.js
ReactDOM.render(
<Router>
<Route component={App2}>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
component={route.main}
/>
))}
</Route>
</Router>,
document.getElementById('content')
);
Then in App2.js
class App2 extends React.Component {
render() {
return (
<div>
<Menu inverted vertical fixed="left">
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
component={route.sidebar}
/>
))}
</Menu>
<Container className="main-container">
{this.props.children}
</Container>
</div>
);
}
}
export default App2;
The example from github was written 2 years ago (look here) and I'am not sure for which particular version it is related. And I'am not sure does it works now (because I am also new with react), but I know that you don't have use this approach to reach this aim, you can use separated component which will contains mainz and sidebar, here my example:
class App2 extends React.Component {
render() {
return (
// Your Menu.
// Your Container.
<div>
{this.props.children}
</div>
);
}
}
class Home extends React.Component {
render() {
return (<div><h1>Home</h1></div>);
}
}
class HomeSidebar extends React.Component {
render() {
return (<div><p>I am a sidebar</p></div>);
}
}
class HomeWithSidebar extends React.Component {
render() {
return (
<div>
<Home />
<HomeSidebar />
</div>
);
}
}
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App2}>
<Route path="/a2" components={HomeWithSidebar} />
</Route>
</Router>,
document.getElementById('content')
);
PS: Don't forget use <Router history={browserHistory}> in your example.
And use IndexRoute in your example or specify another, like /a2 in my example.
Im new to react router myself but I am sure that the routes you are using are incorrect. in the example you give you have 2 different routes that resolve to the same path (/):
ReactDOM.render(
<Router>
<Route path="/" component={App2}>
<Route path="/" components={{main: Home, sidebar: HomeSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
I beleieve this should be something like:
ReactDOM.render(
<Router>
<Route path="/" component={App2}>
<IndexRoute components={{main: Home, sidebar: HomeSidebar}}/>
<Route path="some/other/path" components={{main: Home, sidebar: SomeOtherSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
I hope you know that you are using react-router 1.0.x and it is quite outdated. Current version is 4.x.
Below code works perfectly( based on your example provided).
let Router = ReactRouter.Router;
let RouterContext = Router.RouterContext;
let Route = ReactRouter.Route;
class App2 extends React.Component {
render () {
const { main, sidebar } = this.props;
return (
<div>
<div className="Main">
{main}
</div>
<div className="Sidebar">
{sidebar}
</div>
</div>
)
}
}
class Home extends React.Component {
render() {
return (
<div><h1>Home</h1></div>
);
}
}
class HomeSidebar extends React.Component {
render() {
return (
<div>
<p>I'm a sidebar</p>
</div>
);
}
}
ReactDOM.render(
<Router>
<Route component={App2}>
<Route path="/" components={{main: Home, sidebar: HomeSidebar}}/>
</Route>
</Router>,
document.getElementById('content')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/1.0.3/ReactRouter.min.js"></script>
<div id="content"></div>