Example ....
i Have route React
function App() {
return (
<React.Fragment>
<Router>
<Switch>
<Route exact path="/" component={list} />
<Route exact path="/p/:id" component={Post} />
</Switch>
</Router>
</React.Fragment>
)
}
export default App;
And I Have Route in Laravel
Screenshot : http://prntscr.com/ov80dm
but when i am try .. i get blank page ...
anyone know the solution ?
No, you can't but you can write a wildcard any route in web.php, so that every route get redirected to a single view where the js is imported. Then let the react router work accordingly.
Route::get('/{any}', function () {
return view('base.blade')
})->where('any', '.*');
Related
This is my App.js:
function App() {
return (
<BrowserRouter>
<div>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/creation" element={<Creation />} />
<Route path="/payment" element={<Payment />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
I need to pass a string generated in the "Creation page" to the "Payment page."
Meanwhile, once the string is generated on the creation page, the user should be automatically directed to the payment page. ( I have a solution for this: useNavigate( ) ).
Does anyone know what is the best solution to reach this goal?
I appreciate any help you can provide.
In React Router v6 you can pass parameters to the url your navigating to
navigate(`/payment/${yourString}`);
then in payments:
import { useParams, useNavigate } from "react-router-dom";
const params = useParams();
then you can access your string with params.yourString.
Let's say we have a component Home.jsx
const Home = () => {
return (
<div>
<h1>Home</h1>
</div>
);
};
export default Home;
and our router goes as
const Router = () => (
<>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</>
);
That's works fine! But what if we want to import the element as below in the Route component
views.js
export { default as Home } from "./home";
and modify our routes as follows
import * as views from "../views";
<Routes>
<Route path="/" element={views.Home} />
</Routes>
this piece of code makes following error:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
What's the way out?
Well, I come up with a workaround, and that is use variable as method.
Here it is:
<Route path="/" element={views.Home()} />
I’ve got a ReactJS website in which I am trying to use "#azure/msal-react": "^1.0.0-beta.1", and ran into some issues that have me flummoxed.
Most of my pages are open to the public. Some require login. If I add the MSALAuthenticationTemplate as below (but with interactionType=Redirect), as soon as I start the site, it asks me to login. I thought it would only do that if I hit a route that was in the AuthenticationTemplate.
Using InteractionType Popup causes the SPA to throw an exception on startup
Error: Objects are not valid as a React child (found: object with keys {login, result, error}). If you meant to render a collection of children, use an array instead. in p (at App.tsx:44)
All of my routes are, for some reason, coming back to the home page instead of loading the relevant components, event with the AuthenticationTemplate commented out.
I had this pretty much working using straight Javascript, but was running into ESLint issues when publishing, so I thought Typescript would help me fix those. But now it’s just broke.
render() {
initializeIcons();
return (
<MsalProvider instance={msalClient} >
<div className="d-flex flex-column h-100">
<TopMenu />
<div className="container-fluid flex-grow-1 d-flex">
<div className="row flex-fill flex-column flex-sm-row">
<BrowserRouter>
<MsalAuthenticationTemplate
interactionType={InteractionType.Popup}
errorComponent={this.ErrorComponent}
loadingComponent={this.LoadingComponent}>
<Switch>
<Route path="/addevent">
<AddEvent />
</Route>
<Route path="/mydashboard">
<MyDashboard />
</Route>
</Switch>
</MsalAuthenticationTemplate >
<UnauthenticatedTemplate>
<Switch>
<Route path='/'>
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contactus">
<ContactUs />
</Route>
<Route path="/faq">
<Faq />
</Route>
<Route path="/fetchevents">
<FetchEvents />
</Route>
<Route path="/gettingstarted">
<GettingStarted />
</Route>
<Route path="/partners">
<Partners />
</Route>
<Route path="/privacypolicy">
<PrivacyPolicy />
</Route>
<Route path="/sponsors">
<Sponsors />
</Route>
<Route path="/termsofservice">
<TermsOfService />
</Route>
<Route path="/userstories">
<UserStories />
</Route>
</Switch>
</UnauthenticatedTemplate>
<div>
<Footer />
</div>
</BrowserRouter>
</div>
</div>
</div>
</MsalProvider>
);
Let's start with the UnauthenticatedTemplate. If the user is authenticated, children of the component will not show. So I guess you don't want to use it there. It's typical usage is for Login/Logout button for example.
Another problem is that if you are using MsalAuthenticationTemplate as the parent of the Switch and Route components. The problem is that you are guarding switch and routes from unauthenticated users, but this components should always be available without authentication, if you don't want to protect whole page.
During rendering React will go through your components one by one and first child of the BrowserRouter component it will try to render is MsalAuthenticationTemplate and since user is not authenticated, it will redirect user to login page.
This is quote from react-router docs:
A Route is always technically “rendered” even though it’s rendering null. When the 's path matches the current URL, it renders its children (your component).
Because of this the children of the route will only be rendered if the route will be hit. So you need to put MsalAuthenticationTemplate component as a direct child of the route, or even inside such component:
<Switch>
<Route path="/addevent">
<MsalAuthenticationTemplate
interactionType={InteractionType.Redirect}
authenticationRequest={loginRequest}
>
<AddEvent />
</MsalAuthenticationTemplate>
</Route>
...
</Switch>
As for all the webpages redirected to your home screen, you should add exact keyword to your Home route. This attribute causes it to not match all other routes also. Single '/' matches all your other routes.
In addition to the answer already provided, there is a way (cleaner in my opinion) you can configure MSAL react to take advantage of the router's navigate functions when MSAL redirects between pages in your app.
Here is how it works:
In your index.js file you can have something like so:
import { PublicClientApplication, EventType } from "#azure/msal-browser";
import { msalConfig } from "./authConfig";
export const msalInstance = new PublicClientApplication(msalConfig);
ReactDOM.render(
<React.StrictMode>
<Router>
<ThemeProvider theme={theme}>
<App pca={msalInstance} />
</ThemeProvider>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
As shown, you need to pass msal instance as props to your main App.
Then in your App.js where you setup your routes, you will need to do the following:
import { MsalProvider } from "#azure/msal-react";
import { CustomNavigationClient } from "NavigationClient";
import { useHistory } from "react-router-dom";
function App({ pca }) {
// The 3 lines of code below allow you to configure MSAL to take advantage of the router's navigate functions when MSAL redirects between pages in your app
const history = useHistory();
const navigationClient = new CustomNavigationClient(history);
pca.setNavigationClient(navigationClient);
return (
<MsalProvider instance={pca}>
<Grid container justify="center">
<Pages />
</Grid>
</MsalProvider>
);
}
function Pages() {
return (
<Switch>
<Route path="/addevent">
<AddEvent />
</Route>
<Route path="/mydashboard">
<MyDashboard />
</Route>
<Route path='/'>
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contactus">
<ContactUs />
</Route>
<Route path="/faq">
<Faq />
</Route>
// your other routes
</Switch>
)
}
And here is the helper function used in App.js that enables navigation by overriding the the default function used by MSAL
import { NavigationClient } from "#azure/msal-browser";
/**
* This is an example for overriding the default function MSAL uses to navigate to other urls in your webpage
*/
export class CustomNavigationClient extends NavigationClient{
constructor(history) {
super();
this.history = history;
}
/**
* Navigates to other pages within the same web application
* You can use the useHistory hook provided by react-router-dom to take advantage of client-side routing
* #param url
* #param options
*/
async navigateInternal(url, options) {
const relativePath = url.replace(window.location.origin, '');
if (options.noHistory) {
this.history.replace(relativePath);
} else {
this.history.push(relativePath);
}
return false;
}
}
You can then use AuthenticatedTemplate on your private pages and UnauthenticatedTemplate on the public pages. For example if you have have addEvent.js (private) and Home.js (public), you will have each components like so:
export function Home() {
return (
<>
<AuthenticatedTemplate>
<p>Welcome Home - it's public</p>
</AuthenticatedTemplate>
</>
);
}
export function AddEvent() {
return (
<>
<UnauthenticatedTemplate>
<Typography variant="h6">
Add event - it is a private page
</Typography>
</UnauthenticatedTemplate>
</>
);
}
Here is a complete example on how to use react-router with msal react for your reference.
I am trying to set redirection to default page, but not works. what is the correct way to do this?
const routes = [
{
path:"/",
component:Home,
extract:"true",
redirect:"/home"
},
{
path:"/home",
component:Home
},
{
path:"/service",
component:Service
}
];
html:
<div>
<Router>
<Header />
{routes.map((route) => (
<Route
key={route.path}
path={route.path}
component={route.component}
/>
))}
</Router>
Assuming you are using react-router-dom, I can see one definitive issue with some additional concerns. You may only need to make one change, but I would advise reviewing the rest of your code to ensure the best routing config.
Main Issue: You have to add a redirect to '/home' if you want that component to be the first page to be loaded. This is because when the app is rendered, it sees the default path as '/'.
<Redirect exact from="/" to="/home" />
<Route path="/home">
<Home />
</Route>
While this may solve your problem by itself, here is a more comprehensive solution that should be beneficial to compare your current code against.
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
import home from "./Home";
import service from "./Service";
import header from "./Header";
function App () {
return (
<div>
<Router>
<Header />
<hr />
<Switch>
<Redirect exact from="/" to="/home" />
<Route path="/home">
<Home />
</Route>
<Route exact path="/service">
<Service />
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
As you can see, I would recommend moving the Header outside of the Switch statement and then applying the redirect from / to /home.
Also, please note this configuration is simply an example. It depicts a situation where you are exporting App as a component and does not account for login authorization, so certain aspects of your code may vary.
I have navigation in react and want to redirect to the listing page on click.using this right now which is loading the page
This is my Header.js file
return (
<Link to="/allusers">All Users</Link>
);
This is my App.js file
I imported this
import UsersList from './user/UsersList'; //then i defined
class App extends Component {
render () {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/userlist' component={UsersList} />
</Switch>
</div>
</BrowserRouter>
)
}
}
You can check react-router or #reach/router
For example, in #reach/router, you can use the provided Link component to create the same anchor as in your example:
<Link to="/userlist">All Users</Link>
And create a router with all your routes:
<Router primary={false}>
<Home path="/" />
<AllUsers path="/allusers" />
<NotFound default />
</Router>
https://github.com/reach/router
You can play around with this example: https://reach.tech/router/tutorial/04-router
Same thing can be done with react-router.
This achieved through a client side routing: manipulation of the history object of the browser through client side
This is an example rendering a specific component for specific route
import { BrowserRouter, Route, Link, Switch } from "react-router-dom"
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/allusers" component={AllUsers} />
<Route component={NotFoundPage} />
</Switch>
</BrowserRouter>
// then just pair it up with a navigation bar
<Link to="/">All Users</Link>
<Link to="/allusers">All Users</Link>
These components tied up to a route has access to history object as prop where you can call history.push('/allusers') for other use cases
reference:
https://reacttraining.com/react-router/web/guides/quick-start
You can do that as follows:
goToUserList = () => {
this.props.history.push('/userlist')
}
...
return(
<button onClick={this.goToUserList}>Go User List</button>
)
Hope it helps.