React Router Help: component appears when I would expect it not to - reactjs

I am trying a simple routing with React. My understanding is that with the below, the Navi component being routed should only appear in the root url and not appear in any other url, however this is not the case - no matter the url, the component always appears. Could someone explain what I am missing?
import React, { Component } from "react";
import Home from "./Home";
import Navi from "./Navi";
import Welcome from "./Welcome";
import logo from "./logo.svg";
import "./App.css";
import { Route, BrowserRouter as Router } from "react-router-dom";
class App extends Component {
constructor() {
super();
this.state = { user: "kungpow" };
}
render() {
return (
<div>
<Router>
<Navi user={this.state.user} />
<Route exact link="/" Component={Navi} />
</Router>
<Home user={this.state.user} />
<Welcome user={this.state.user} />
</div>
);
}
}
export default App;

Your are missing path prop. Replace link with path prop.
<Router>
<Route exact path="/" render={() => <Navi user={this.state.user} />} />
</Router>

Related

React Router give blank page

I Try this code to companion tow composts in react using routs but it render blank page
import React from 'react';
import { Routes , Route } from 'react-router-dom';
// import * as BooksAPI from './BooksAPI'
import './App.css';
import SearchBook from './components/SearchBook';
import Main from './components/Main';
class BooksApp extends React.Component {
state = {
showSearchPage: false
}
render() {
return (
<div className="Root">
<Routes>
<Route exact path="/" element={<Main />} />
<Route path="/search" element = {<SearchBook />}/>
</Routes>
</div>
)
}
}
export default BooksApp
when i tried to render the components directly like this
render() {
return (
<div>
<Main />
<SearchBook />
</div>
)
}
it worked fine
It is better to configure all the routes inside the App.js. If your are providing routes inside BooksApp component. Please make sure, you have imported and called the BooksApp component in the App.js.
You need to import BrowserRouter and wrap all routes inside the BrowserRouter as like given below,
import React from 'react';
import { Routes , Route, BrowserRouter as Router } from 'react-router-dom';
// import * as BooksAPI from './BooksAPI'
import './App.css';
import SearchBook from './components/SearchBook';
import Main from './components/Main';
class BooksApp extends React.Component {
state = {
showSearchPage: false
}
render() {
return (
<div className="Root">
<Router>
<Routes>
<Route exact path="/" element={<Main />} />
<Route path="/search" element = {<SearchBook />}/>
</Routes>
</Router>
</div>
)
}
}
export default BooksApp

How to stop random links from opening with react-router?

I am new to React and practicing with an online website for repairing appliances. I have used react-router and created all my routes in a separate file.
I have a problem though, I can open any link from the address bar like:
http://localhost:3000/<randomword>
I only want routes to be opened that I have declared in my routes component while if I type http://localhost:3000/something, I get an empty page with my header and footer in it.
here are my codes:
Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";
import Routes from './Routes';
import './index.css';
const App = () => {
return(
<BrowserRouter>
<Routes />
</BrowserRouter>
)
}
ReactDOM.render(<App/>,document.getElementById('root'));
App.js:
import React, {Component} from 'react';
import { Route, BrowserRouter } from 'react-router-dom';
import Layout from './Containers/Layout';
import LandingPage from './Containers/Pages/LandingPage';
import About from './Containers/Pages/About';
import Cities from './Containers/Pages/Cities';
import Discount from './Containers/Pages/Discount';
class Routes extends Component {
render(){
return (
<div>
<Layout>
<BrowserRouter>
<Route path="/" render={props => <LandingPage {...props} />} exact component={LandingPage}/>
<Route path="/About" component={About}/>
<Route path="/Cities" component={Cities}/>
<Route path="/Discount" component={Discount}/>
</BrowserRouter>
</Layout>
</div>
);
}
};
export default Routes;
Layout.js:
import React, { Component } from 'react';
import Header from "./Layouts/Header";
import Footer from './Layouts/Footer';
import './Layout.css';
export default class Layout extends Component {
constructor(){
super();
this.state= {
}
}
render() {
return (
<div className="page-container">
<Header/>
<div className="content-wrap">
{this.props.children}
</div>
<Footer/>
</div>);
}
}
Can someone help me figure out how I should stop random random pages to be opened from addressbar?
Just want to start by saying I'm completely self-taught with React so I apologize if this answer is incorrect. However, in my experience with react-router I always have a Switch inside of my BrowserRouter. So your Routes class in app.js should something like this:
class Routes extends Component {
render(){
return (
<div>
<Layout>
<BrowserRouter>
<Switch>
<Route path="/" render={props => <LandingPage {...props} />} exact component={LandingPage}/>
<Route path="/About" component={About}/>
<Route path="/Cities" component={Cities}/>
<Route path="/Discount" component={Discount}/>
</Switch>
</BrowserRouter>
</Layout>
</div>
);
}
};
Just be sure you don't forget to update your imports to
import { Switch, Route, BrowserRouter } from 'react-router-dom';
import { Redirect } from "react-router-dom"
<Route path="/not-found" component={notFound-Component} />
<Redirect to="/not-found" />
This will always redirect you to 404 component if route is not present just make a 404 component and u should add the redirect at the end after all routes are defined

Component not getting loaded in react routing

Im trying to implement routing in react.
Here's my index.js file
import React from 'react';
import {render} from 'react-dom';
import { BrowserRouter,Route, Switch, withRouter,Redirect } from 'react-router-dom';
import {Home} from './components/Home.jsx';
import {AddUser} from './components/AddUser.jsx';
class App extends React.Component {
render() {
return(
<BrowserRouter>
<Switch>
<Route path="/" exact render={() => <Redirect to='/home' />} />
<Route path="/home" exact component={Home} />
<Route path="/adduser" exact component={AddUser} />
</Switch>
</BrowserRouter>
);
}
}
render(<App/>, document.getElementById('root'));
This my home component file
import React from 'react';
export default class Home extends React.Component {
constructor() {
super();
this.state = {
users : []
}
}
render() {
return (
<div>hello</div>
);
}
}
Application redirects as expected but the component is not getting loaded.
There are no errors in the console, I could find various examples of react routing most of them were of previous router versions.
Kindly help me understand this issue.
Thanks in advance
When importing the default export do not use {}
So, since you export your components as default, you should use
import Home from './components/Home.jsx';
import AddUser from './components/AddUser.jsx';
demo at https://codesandbox.io/s/5wqx9x2724
In general see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

React - inserting variable into Route path

I have an app that I am creating and am wondering how you would insert variables into the <Route path={insert variable here} component={myProfile}> I am trying to create a myProfile page and I am trying to get it so when they click onto the link, it redirects them to http://mywebsite.com/userId but when I try to create a Route with a variable in the path argument, it does not return the component I am trying to render when on that path.
routes.js
import { Meteor } from "meteor/meteor"
import React from "react";
import { withRouter, Switch, BrowserRouter, Route, Redirect, Link } from "react-router-dom";
import Login from "../ui/authentication/Login";
import Signup from "../ui/authentication/Signup";
import Home from "../ui/Home";
import { SubjectRoutes } from "../ui/subjectRoutes/subjectRoutes";
import AddNote from "../ui/AddNote";
import myProfile from "../ui/myProfile";
import NotFound from "../ui/NotFound";
export default class Routes extends React.Component{
renderSubjectRoutes(subjects){
return subjects.map((subject) => {
return <Route key={subject.name} path={subject.path} component={subject.component}/>
})
}
render(){
return (
<div>
<BrowserRouter>
<Switch>
<Login path="/login" />
<Signup path="/signup" />
<Route path="/" component={Home} exact/>
{this.renderSubjectRoutes(SubjectRoutes)}
<AddNote path="/addNote"/>
<myProfile path={Meteor.userId()} /> //<-- Here
<NotFound />
</Switch>
</BrowserRouter>
</div>
)
}
}
Menu.js
import { Meteor } from "meteor/meteor"
import React from "react";
import { withRouter, Link } from "react-router-dom";
import { SubjectRoutes } from "./subjectRoutes/subjectRoutes";
import AddNote from "./AddNote";
class Menu extends React.Component{
renderMenu(items){
return items.map((item) => {
return <p key={item.name}><Link to={item.path}>{item.name}</Link></p>
})
}
render(){
return(
<div>
<h1>Menu</h1>
{this.renderMenu(SubjectRoutes)}
<p><Link to="/addNote">Add a Note</Link></p>
<p><Link to={Meteor.userId()}>My Profile</Link></p>
</div>
)
}
}
export default withRouter(Menu)
You are creating way more work for yourself, and this is the wrong way to add variables to route. What you're looking to do is add params to your route. In your case, you would want it to look something like this.
<Route path="/user/:userId" />
The : is what denotes that it is a parameter, ready to render a path based on the userId. So if you went to route /user/123 - it would be able to render user 123's data.
Here's some documentation to help you out.
https://reacttraining.com/react-router/web/example/url-params

URL change but page does not refresh

I am using react router 4. I have two components 1- ShopLogin 2- Shopper. I am trying to redirect from ShopLogin component to Shopper component after button click.
Everything is working fine. URL is also changing after button click. I am able to see 'Hello' also.
But the problem is i am able to see both component on browser after button click. component is not refreshing. not sure why it is happening. Below are my code.
import React from 'react';
import PropTypes from 'prop-types';
export class ShopLogin extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
SignIn(e) {
e.preventDefault();
this.context.router.history.push('/shopper');
}
render() {
return (
<div>
<button onClick={this.SignIn.bind(this)}>SignIn</button>
</div>
);
}
}
ShopLogin.contextTypes = {
router: PropTypes.object
}
export default ShopLogin;
My Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ShopLogin from './ShopLogin';
import Shopper from './Shopper';
import { HashRouter,Route } from 'react-router-dom';
ReactDOM.render((
<HashRouter>
<div>
<Route path="/" component={ShopLogin} />
<Route path="/shopperlogin" component={ShopLogin} />
<Route path="/shopper" component={Shopper} />
</div>
</HashRouter>
), document.getElementById('root'))
My Shopper.js
import React, { Component } from 'react';
export class Shopper extends Component {
constructor(props)
{
super(props);
this.state = {
};
}
render()
{
return (
<div>
Hello </div>
);
}
}
export default Shopper;
It will show multiple components since on the route '/shopper'. The Routes checks successfully to the ShopLogin Component with the path '/' and it checks successfully to the Shopper Component with the path '/shopper'.
I would create a parent Component e.g. Main that just presents the child components and define the routes like this
import IndexRoute from react-router
import { HashRouter,Route, IndexRoute } from 'react-router-dom';
resort your routes to
<HashRouter>
<Route path='/' component={Main}>
<Route path='/shopper' component={Shopper} />
<IndexRoute component={ShopLogin} />
</Route>
</HashRouter>
Create your parent component for ShopLogin and Shopper components
class Main extends Component {
render(){
return (
<div>
{this.props.children}
</div>
)
}
Try to reorder your routes and use the exact attribute and wrap all the routes with a Switch.
<HashRouter>
<div>
<Switch>
<Route path="/" component={ShopLogin} />
<Route exact path="/shopper" component={Shopper} />
<Route path="/shopperlogin" component={ShopLogin} />
</Switch>
</div>
</HashRouter>

Resources