React routing not working in react boilerplate - reactjs

I am trying to route but it is not working it shows a blank page
here is the code
when I hit localhost:3000/home it is not showing anything
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from "react-router-dom";
const Home = () =>{
return(
<div>
<p>Home</p>
</div>
);
}
class App extends Component {
render() {
return (
<Router>
<Route path='/home' Component={Home}/>
</Router>
);
}
}
export default App;

component prop in <Route /> is case-sensitive, make it lower case
class App extends Component {
render() {
return (
<Router>
<Route path='/home' component={Home}/>
</Router>
);
}

Related

About retrieving page name in index page

Goal:
When you write url "https://react-router-with-params-aq6utk.stackblitz.i/test" I would like to display the page test.
Problem:
Is it possble to retrieve the value 'test' and use it at app.js?
Today it doesn't work.
Info:
*Newbie in reactjs
Stackblitz:
https://stackblitz.com/edit/react-uaofyx?file=src%2FApp.js
app.js
import React, { Component } from 'react';
import { HomeComponent } from './Containers/HomeComponent';
import DashboardComponent from './Containers/DashboardComponent';
import ContactComponent from './Containers/ContactComponent';
import { Switch, Route, Link } from 'react-router-dom';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
};
}
render() {
console.log(this.props.id);
console.log(this.props);
if (this.props.id === 'test') {
return (
<div>
<Switch>
<Route path="/test" exact component={ContactComponent} />
</Switch>
</div>
);
} else {
return (
<div>
<Switch>
<Route
path="/dashboard/:id"
render={(props) => (
<DashboardComponent {...props} isAuthed={true} />
)}
/>
<Route path="" exact component={HomeComponent} />
</Switch>
</div>
);
}
}
}
export default App;
ContactComponent.js
import React from 'react';
export const ContactComponent = ({ value }) => {
const name = 'CONTACT';
return <h1>{name}</h1>;
};
DashboardComponent.js
import React, { Component } from 'react';
class DashboardComponent extends Component {
constructor(props) {
super(props);
console.log(this.props.match.params.id);
}
render() {
return <div>Hello from dashboard.. ffff</div>;
}
}
export default DashboardComponent;
HomeComponent.js
import React from 'react';
export const HomeComponent = ({ value }) => {
const name = 'rajesh';
return <h1>{name}</h1>;
};
There are some issues with the implementaion of Route. also, you export the ContactComponent without default but you used it in App.js with the default import statement.
The working code:
import React, { Component } from 'react';
import { HomeComponent } from './Containers/HomeComponent';
import DashboardComponent from './Containers/DashboardComponent';
import { ContactComponent } from './Containers/ContactComponent';
import { Switch, Route, Link, BrowserRouter as Router } from 'react-router-dom';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path="/test" exact component={ContactComponent} />
<Route
path="/dashboard/:id"
component={(props) => <DashboardComponent {...props} isAuthed={true} />}
/>
<Route path="" exact component={HomeComponent} />
</Switch>
</Router>
);
}
}
export default App;
check the live version on stackblitz
Explanation:
If you export a variable with the default keyword, so you need to import it without {}
const first = 'first'
const second = 'second'
export first
export default second
Now in usage:
import second, {first} from 'myVariables';
Also, your route configuration with react-router-dom will look like this:
<BrowserRouter>
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/about" exact={true} component={About} />
<Route path="/contact" exact={true} component={Contact} />
// rest of the routes ...
</Switch>
</BrowserRouter>
Note: Your App.js component is the root component so there aren't any props with it.

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

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>

Redirect from React's Context API component

I am trying to redirect from my context following a failed update of the state from the a cookie.
import React, { createContext, Component } from 'react';
import { withRouter } from "react-router-dom";
import Cookies from 'universal-cookie';
export const MyContext = createContext();
const cookies = new Cookies();
class MyProvider extends Component {
componentDidMount() {
this.setStateFromCookie();
}
setStateFromCookie = () => {
try {
this.setState({ data: cookies.get('my-cookie')['data'] });
} catch(error) {
console.log(error);
this.props.history.push('/');
}
return
};
render() {
return (
<MyContext.Provider value={{...this.state}}>
{this.props.children}
</MyContext.Provider>
);
}
}
export default withRouter(MyProvider);
I am using a withRouter hook to this.props.history.push('/'), becuase the context is wrapping the router
class MyApp extends Component {
render() {
return (
<BrowserRouter>
<MyProvider>
<div className="MyApp">
<Router>
<Route exact path='/' component={Index} />
<Route exact path='/dashboard' component={Dashboard} />
</Router>
</div>
</MyProvider>
</BrowserRouter>
);
}
}
export default MyApp;
The problem is that the redirect to the home page following the error, but the home page isn't rendering.. I still see the dashboard page.
Any idea what is going on and how to fix this
The issue is that you have a nested Router wrapping your Routes. You need to remove that and then everything will work fine
<BrowserRouter>
<MyProvider>
<div className="MyApp">
<Route exact path='/' component={Index} />
<Route exact path='/dashboard' component={Dashboard} />
</div>
</MyProvider>
</BrowserRouter>
When you use a nested Router, and try to navigate from Provider, the history used by Provider is being provided by BrowserRouter and hence it isn't able to communicate to the Routes whcih are dependent on the inner <Router> component for history.
Using a single router wrapping your components solves this issue

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>

implement react-router within typescript app

I have a working copy of the same code only differs come from typescript.
And this the code below somehow and exception message..
import * as React from 'react';
import Home from '../Home/Home';
import User from '../User/User';
import {
BrowserRouter as Router,Route,Link,Switch} from 'react-router-dom'
class Layout extends React.Component<{},{}> {
render() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/" component={Home} />
<Route path="/user/:id" userid="25" component={User}/>
<Route component={Notfound}/>
</Switch>
</div>
</Router>
);
}
}
and one of my component, home.tsx:
import * as React from 'react';
class Home extends React.Component<{},{}> {
render() {
return (
<div className="App">
Welcome Home Page!
</div>
);
}
}
Whats wrong here ?
Here is how I fixed the problem. As a commenter explained, there is some confusion for the compiler on how to explicitly handle passing in props.
App.tsx:
import * as React from 'react';
import './App.css';
interface State { }
// tslint:disable-next-line
class App extends React.Component<any, State> {
render() {
return (
<div className="App">
HIIIII
</div>
);
}
}
export default App;
index.tsx:
...
ReactDOM.render(
<Router>
<div>
<Route path="/" component={App} />
</div>
</Router>,
document.getElementById('root') as HTMLElement
);
I have not found a better solution yet. But this will indeed work.

Resources