React router params and querys is not working - javascript

From last couple of days i was finding a solution for this problem.what is happening here is i want dynamic link.you can see below here:
<Route path="/edit/:username" component={EditExpensePage} />
But when I go to /edit/12, I'm getting this error:
GET http://127.0.0.1:8080/edit/bundle.js net::ERR_ABORTED
Here is my code:
import React from 'react';
import { BrowserRouter, Route, Switch, Link, NavLink } from 'react-router-dom';
import ExpenseDashboardPage from '../components/ExpenseDashboardPage';
import AddExpensePage from '../components/AddExpensePage';
import EditExpensePage from '../components/EditExpensePage';
import HelpPage from '../components/HelpPage';
import NotFoundPage from '../components/NotFoundPage';
import Header from '../components/Header';
const AppRouter = () => (
<BrowserRouter>
<div>
<Header />
<Route path="/" component={ExpenseDashboardPage} exact={true} />
<Route path="/create" component={AddExpensePage} />
<Route path="/edit/:username" component={EditExpensePage} />
<Route path="/help" component={HelpPage} />
</div>
</BrowserRouter>
);
export default AppRouter;

It looks like you're loading your bundle.js file with a relative URL.
So when you load the page http://127.0.0.1/Home (or whatever) it resolves as http://127.0.0.1/bundle.js, which is correct.
However when you load the page http://127.0.0.1/edit/12 it resolves as http://127.0.0.1/edit/bundle.js, which is incorrect.
Make the <script tag use an absolute URL.

Related

Web page is blank (Problem with react-router)

I am trying to learn MERN mainly react by following a tutorial (https://www.youtube.com/watch?v=7CqJlxBYj-M) and I have followed the code exactly but when I run the server and open the web page it is blank.
I know the problem is with the four React route paths because if I remove them the web page displays the navbar. I also get no errors when running the server.
this is the app.js file code:
import React from 'react';
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter as Router, Route,} from "react-router-dom";
import Navbar from "./components/navbar.component"
import ExercisesList from "./components/exercises-list.component";
import EditExercise from "./components/edit-exercise.component";
import CreateExercise from "./components/create-exercise.component";
import CreateUser from "./components/create-user.component";
function App() {
return (
<Router>
<div className="container">
<Navbar />
<br/>
<Route path="/" exact component={ExercisesList} />
<Route path="/edit/:id" component={EditExercise} />
<Route path="/create" component={CreateExercise} />
<Route path="/user" component={CreateUser} />
</div>
</Router>
);
}
export default App;
This is the code for create-exercise:
import React, { Component } from 'react';
export default class CreateExercise extends Component{
render() {
return (
<div>
<p>You are on the create exercises List componentt</p>
</div>
)
}
}
The other three have the same code.
This is the link to the github containing the tutorial's code:
https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqa3VfM2thaXc4b1RoODUxWkh0MXprN2NFV3E2QXxBQ3Jtc0trbTdTQll1WmVFQ1hRb0ZOVWlUVVROUG1ta2RranJocVFmektvb0F0VWpKQjNWY0tIelBuZ1ZLNDU5VVFhSVZiS3VGTnJHT19ja0NYdVI3OFdkZVVQS0ZoLV8wQkxhT2xqeS0yakNPSXNyZjlLTW5Vbw&q=https%3A%2F%2Fgithub.com%2Fbeaucarnes%2Fmern-exercise-tracker-mongodb
In React-Router version 6 you need to use element
https://reactrouter.com/docs/en/v6/getting-started/tutorial#add-some-routes
Example:
<Route path="/" element={<App />} />
<Route path="expenses" element={<Expenses />} />
<Route path="invoices" element={<Invoices />} />

React Router does not recognize direct address line changing in laravel

I use React Router and Laravel. When I navigate throught Link elements all OK, but when I change browser address line to manually show another component Laravel shows it defalt 404 page.
This is default web.php content, in welcome.blade.php I inlcude js/app.js file:
Route::get('/', function () {
return view('welcome');
});
This is my App.js content:
import React from 'react';
import { Switch, Route } from "react-router-dom";
import Signin from "../../containers/Signin";
import Signup from "../../containers/Signup";
import Error from "../../containers/Error";
import Courses from "../../containers/Courses";
import Course from "../../containers/Course";
import Quiz from "../../containers/Quiz";
import Header from "../Header";
import "./App.css";
import Library from "../../containers/Library";
import QuizResults from "../../containers/QuizResults";
import Main from "../Main";
import StudentsList from "../../containers/StudentsList";
function App()
{
return (
<div className="App">
<Header isLogged={false}/>
<Switch>
<Route exact path='/' component={Signin} />
<Route path='/signup' component={Signup} />
<Main>
<Route path='/courses' component={Courses} />
<Route path='/course/:id' component={Course} exact/>
<Route path='/quiz' component={Quiz} />
<Route path='/library' component={Library} />
<Route path='/quiz-results' component={QuizResults} />
<Route path='/students' component={StudentsList} />
</Main>
<Route component={Error} />
</Switch>
</div>
);
}
export default App;
app.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
So, how to force React Router react on direct browser address line change?
as your working with SPA so you need to configure your web.php like this
Route::any('{all}', function () {
return view('welcome');
})
->where('all', '^(?!api).*$')
->where('all', '^(?!storage).*$');
then react router will catch all routes
and here api and storage routes is exclude from catch so you can use storage files and api to make call api

Installed React-Router - The URL changes, but not the view

I am using React-Router for the first time. I am trying to get the buttons on the homepage to go to its respective URL, but When I click on a button, the URL changes, but not the view. I don't get any errors on the console, either. I was wondering if somebody can point out what is happening. I wrapped each button with a link, and assigned the path it needs to go to when clicked. I was wondering if anyone can point out what I am doing wrong.
Homepage.js
import React from 'react';
import {Link} from "react-router-dom"
class HomePage extends React.Component {
render(){
return (
<div>
<h1>Welcome</h1>
<p>Please select a category </p>
<Link to="/ProgrammingJokes">
<button>Programming Jokes</button>
</Link>
<Link to="/DadJokes">
<button>Dad Jokes</button>
</Link>
<Link to="/SportsJokes">
<button>Sports Jokes</button>
</Link>
</div>
)
}
}
export default HomePage;
App.js
import React from 'react';
import HomePage from './components/HomePage'
import DadJokesApi from './components/DadJokesApi'
import SportsJokesApi from './components/SportsJokesApi'
import ProgrammingJokesApi from './components/ProgrammingJokesApi';
import { Route, Switch} from "react-router-dom";
function App() {
return (
<main>
<Switch>
<Route path="/" component={HomePage} />
<Route path="/DadJokes" component={DadJokesApi} />
<Route path="/SportsJokes" component={SportsJokesApi} />
<Route path="/ProgrammingJokes" component={ProgrammingJokesApi} />
</Switch>
</main>
);
}
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>,
document.getElementById('root')
);
Try placing your root route at the end of the list.
Since:
A <Switch> looks through its children <Route>s and renders the first
one that matches the current URL.
From https://reacttraining.com/react-router/web/guides/quick-start
<Switch>
<Route path="/DadJokes" component={DadJokesApi} />
<Route path="/SportsJokes" component={SportsJokesApi} />
<Route path="/ProgrammingJokes" component={ProgrammingJokesApi} />
<Route path="/" component={HomePage} />
</Switch>
Your Switch is matching with the first route every time. You need to use
<Route exact path = '/' component = {Component}/>
You can use the exact property on your routes.
When true, will only match if the path matches the location.pathname exactly.
You can read more here https://reacttraining.com/react-router/web/api/Route/exact-bool
The result must be something like this:
<Route path="/DadJokes" exact component={DadJokesApi} />

React Router v5 nested routes not found

I'm having problems trying to make a simple setup to run. I have used "react-router-dom" because it claims to be the most documented router around.
Unfortunately, the documentation samples are using functions instead of classes and I think a running sample will not explain how routes have changed from previous versions... you need a good sight!. Btw, there are a lot of breaking changes between versions.
I want the following component structure:
Home
Login
Register
Recipes
Ingredients
Have the following components:
index.js (works fine)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
ReactDOM.render((
<BrowserRouter>
<Route component={App}/>
</BrowserRouter>
), document.getElementById('root'));
App.js (fine)
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home'
import Recipes from './recipes/Recipes'
import Ingredients from './ingredients/Ingredients'
class App extends React.Component {
render() {
return (
<div id="App">
<Switch>
<Route exact path='/home' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
</div>
);
}
}
export default YanuqApp;
Ingredients and Recipes components working fine, so I'll skip from here
Home.js - The problem starts here. Home itself loads correctly, but once Login or Register links are clicked, it shows "Not found!" (fallback route in App.js)
import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import Register from './account/register'
import Login from './account/login'
class Home extends React.Component {
render() {
return (
<div>
<div>
This is the home page...<br/>
<Link to='/home/login'>Login</Link><br />
<Link to='/home/register'>Register</Link><br />
</div>
<Switch>
<Route path='/home/login' component={Login} />
<Route path='/home/register' component={Register} />
</Switch>
</div>
);
}
}
export default Home;
Login and register are very similar:
import React from 'react';
class Login extends React.Component {
render() {
alert("login");
return (
<div>Login goes here...</div>
);
}
}
export default Login;
And cannot figure why Login and Register are not found. I have tried also defining routes as:
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
(don't see the gain on using match, as it renders as the expected "/home/register"), but the problem persists in identical way
I think it's because of the exact flag on the Route for home. It does not match the /home exact so it goes to the default not found page.
try to add this in App.js
<Switch>
<Route exact path='/' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
to this is work
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
you should provide match as the props because cont access directly to the match to used it you should provide a match as this following
const namepage=({match})=>{
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
})

React Router Switch not rendering specific component

I have a React app that is currently using react-router#4.2.0 and I'm struggling with rendering a specific component when the URL changes.
When I try to visit /locations/new it returns with a PropTypes error from the CityList component. I have tried adding in exact to the Route component within LocationsWrapper and then Main config too, however, this then influences other routes - such as /locations to become null.
// BrowserRouter
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store";
import Navbar from "./components/Core/Navbar";
import Routes from "./config/routes";
render(
<Provider store={store}>
<BrowserRouter>
<div style={{ backgroundColor: "#FCFCFC" }}>
<Navbar />
<Routes />
</div>
</BrowserRouter>
</Provider>,
document.getElementById("root")
);
// Router config - ( Routes )
import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "../components/Home";
import Locations from "../components/Locations";
import CityList from "../components/CityList";
import CreateLocation from "../components/CreateLocation";
import Locale from "../components/Locale/index";
import Profile from "../components/Profile";
import NoMatch from "../components/Core/NoMatch";
import requireAuth from "../components/Core/HOC/Auth";
const LocationsWrapper = () => (
<div>
<Route exact path="/locations" component={Locations} />
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
</div>
);
const Main = () => (
<main>
<Switch>
<Route exact path="/" component={requireAuth(Home)} />
<Route path="/locations" component={LocationsWrapper} />
<Route path="/locale/:id" component={Locale} />
<Route path="/profile" component={requireAuth(Profile, true)} />
<Route component={NoMatch} />
</Switch>
</main>
);
export default Main;
Am I best avoiding <Switch> entirely and implementing a new method for routes that are undefined - such as 404s?
Yes, this will definitely return first
<Route path="/locations/:id" component={CityList} />
In react-router 4 there is no concept of index route, it will check each and every routes so in your defining routes are same
<Route path="/locations/new" component={CreateLocation} />
<Route path="/locations/:id" component={CityList} />
both path are same '/location/new' and '/location/:id' so /new and /:id are same params.
so at last 'CityList' will return
You can define like this
<Route path="/locations/create/new" component={CreateLocation} />
<Route path="/locations/list/:id" component={CityList} />
Pretty sure your route is not working cause you are also matching params with /locations/new with /locations/:id so then 'new' becomes Id param.
Try changing this
<Route path="/locations/new" component={CreateLocation} />
To something like this
<Route path="/locs/new" component={CreateLocation} />
Just a suggestion hope this may help

Categories

Resources