Required context `router` was not specified. Check the render method of `RoutingContext` - javascript

My app is ES6 React application with react-router. I want to redirect user to a different page after a small delay. Here is my React component:
import React from 'react'
import { Navigation } from 'react-router'
export default class Component extends React.Component {
render () {
return (
<div>Component content</div>
)
}
componentDidMount () {
setTimeout(() => {
// TODO: redirect to homepage
console.log('redirecting...');
this.context.router.transitionTo('homepage');
}, 1000);
}
}
Component.contextTypes = {
router: React.PropTypes.func.isRequired
}
And react-router routing table:
render(
<Router>
<Route path='/' component={ App }>
<IndexRoute component={ Component } />
</Route>
</Router>
, document.getElementById('app-container'));
The issue is that 'router' property is not passed into the component. Chrome console's content is:
Warning: Failed Context Types: Required context `router` was not specified in `Component`. Check the render method of `RoutingContext`.
redirecting...
Uncaught TypeError: Cannot read property 'transitionTo' of undefined
React version is 0.14.2, react-router version is 1.0.0-rc4
Where do I make mistake?

Im not a react-router expert by any means, but I had the same issue earlier today. I am using React 0.14.2 and React-Router 1.0 (this just came out in the last couple of days, if not more recently). While debugging I noticed that the props on the React component includes history (the new style of navigation - https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md)
I am also using TypeScript, but my code looks like the following:
import React = require('react');
import Header = require('./common/header.tsx');
var ReactRouter = require('react-router');
interface Props extends React.Props<Home> {
history: any
}
class Home extends React.Component<Props, {}> {
render(): JSX.Element {
return (
<div>
<Header.Header MenuItems={[]} />
<div className="jumbotron">
<h1>Utility</h1>
<p>Click on one of the options below to get started...</p>
{<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/remoteaccess') }>Remote Access</a>}
{<a className="btn btn-lg" onClick={() => this.props.history.pushState(null, '/bridge') }>Bridge</a>}
</div>
</div>
);
}
}
module.exports = Home;

I'm inclined to say that this.context.router doesn't exist anymore. I've run into the same problem and it looks like we're supposed to implement these features using this.context.history as well as this.context.location. If I get something working, I'll try updating this response.

See the 1.0.0 upgrade guide and use this.props.history with pushState or replaceState. context is used for other components (not route components).
From the upgrade guide :
// v1.0
// if you are a route component...
<Route component={Assignment} />
var Assignment = React.createClass({
foo () {
this.props.location // contains path information
this.props.params // contains params
this.props.history.isActive('/pathToAssignment')
}
})

Related

react.js & django, useParams unable to navigate to the page

I am current building a react app with django, I am trying to navigate from the HomePage to the DataPage with corrsponding id. However, it return Page not found error. I am using react-router-dom v6.
Using the URLconf defined in robot.urls, Django tried these URL patterns, in this order:
admin/
api/
api-auth/
homepage
homepage/data
The current path, homepage/data/54, didn’t match any of these.
Here is my App.js
export default class App extends Component {
constructor(props) {
super(props);
}
renderHomePage() {
return (
<HomePage />
);
}
render() {
return (
<BrowserRouter>
<Routes>
<Route exact path='homepage/' element={this.renderHomePage()} />
<Route path='homepage/data/:id' element={<DataPage />} />
</Routes>
</BrowserRouter>
)
}
}
const appDiv = document.getElementById("app");
render(<App />, appDiv);
And I want to navigate to the DataPage below:
const EmtpyGrid = theme => ({
Grid: { ... }
});
function DataPage(props) {
const { classes } = props;
const { id } = useParams();
return (
<div>
... some material ui components ...
<div/>
)
};
DataPage.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(EmtpyGrid)(DataPage);
I was thinking whether I need configure my url.py in frontend as well, and I need to define a designated value for {id} returned from the materialui component first. Perhaps I need a button or <Link><Link/> for the navigation instead of just simply typing in the url? Still, no luck after many attempts. I am so confused right now.
If you know what is wrong with my code, please feel free to leave a comment. Thanks
After many tries and checking documents, I don't really need to configure my urls.py. I only things that I am missing is to put a parameter in my naviagate() from onRowClick={((rowData, event) => {navigate('data/');})} to onRowClick={((rowData, event) => {let id = event.sample_ID; navigate('data/' + id)})}; I was thinking the problem too complicated.
Thanks you guys for sharing!

Navigate to welcome page after login page using React Router Dom v6

I'm a beginner learning React and using React v 17.0.2, react-router-dom v 6.0.2. I'm following a course made for react-router-dom v4. I'm not able to get page navigation working if I try to navigate from a successful login to append a welcome message to the url. In v4 this is achieved by a {this.props.history.push("/welcome") method. I'm not able to something equivalent in V6. Specifically, I would like to know how to handle the loginClicked method.
Based on the helpful guidance from Himanshu Singh, I tried the following:
import { computeHeadingLevel } from '#testing-library/react'
import React, { Component } from 'react'
import { BrowserRouter as Router, Routes, Route, useNavigate } from 'react-router-dom'
class TodoApp extends Component {
render() {
return (
<div className="TodoApp">
<Router>
<Routes>
<Route path="/" exact element={<LoginComponent />} />
<Route path="/enlite" element={<LoginComponent />} />
<Route path="/welcome" element={<WelcomeComponent />} />
</Routes>
</Router>
{/* <LoginComponent /> */}
</div>
)
}
}
class WelcomeComponent extends Component {
render() {
return <div>Welcome to Enlite</div>
}
}
class LoginComponent extends Component {
constructor(props) {
super(props)
this.state = {
username: 'testuser',
password: '',
hasLoginFailed: false,
showSuccessMessage: false
}
this.handleChange = this.handleChange.bind(this)
this.loginClicked = this.loginClicked.bind(this)
}
handleChange(event) {
this.setState(
{
[event.target.name]
: event.target.value
})
}
**loginClicked() {
if (this.state.username === 'testuser' &&
this.state.password === 'dummy') {
function HandlePageNav() {
let navigate = useNavigate()
navigate('/welcome')
}
**HandlePageNav();**
}
else {
this.setState({ showSuccessMessage: false })
this.setState({ hasLoginFailed: true })
}
}**
render() {
return (
<div>
{this.state.hasLoginFailed && <div>Invalid Credentials</div>}
{this.state.showSuccessMessage && <div>Welcome to Enlite</div>}
User Name: <input type="text" name="username" value={this.state.username} onChange={this.handleChange} />
Password: <input type="password" name="password" value={this.state.password} onChange={this.handleChange} />
<button onClick={this.loginClicked}>Login</button>
</div>
)
}
}
export default TodoApp
This gives the following error:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug
and fix this problem.
Basically calling hooks in class components is not supported. I also tried to completely do away with the function like this:
loginClicked() {
if (this.state.username === 'testuser' &&
this.state.password === 'dummy') {
let navigate = useNavigate()
navigate('/welcome')
}
else {
this.setState({ showSuccessMessage: false })
this.setState({ hasLoginFailed: true })
}
}
This gives a compile error:
Line 85:32: React Hook "useNavigate" cannot be called in a class
component. React Hooks must be called in a React function component or
a custom React Hook function react-hooks/rules-of-hooks Line 89:13:
'HandlePageNav' is not defined
no-undef
The above makes me wonder if I need to refactor my entire code into a function component or if there's a way to achieve this page navigation but keeping the class component. Other than that I would appreciate any help or insights on this problem. Thanks in advance.
UseNavigate Hook will not work here because hooks are meant to be used in functional components not class components.
What you can do for now is, since no proper doc is provided for class component
Try to use Functional Components : the most easiest way
Use a HOC component around the class component and pass history and other necessary props to it through that component.
Note: Here I tried second approach. You can follow this: https://codesandbox.io/s/snowy-moon-30br5?file=/src/App.js

React: Problem in dynamic nested routing. How to solve this error?

I am getting the following error while trying to implement dynamic routing in React JS.
The required files are:
Assignment.js
import React, { Component } from 'react';
import Users from './containers/Users/Users';
import Courses from './containers/Courses/Courses';
import {Route, Link, Switch, Redirect} from 'react-router-dom';
import Course from './containers/Course/Course';
class Assignment extends Component{
render(){
return(
<div>
<ul>
<li><Link to ="/Users"> Users </Link></li>
<li><Link to ="/Courses"> Courses </Link></li>
</ul>
<Switch>
<Route path ="/Users" component = {Users}/>
<Route path ="/Courses" exact component = {Courses}/>
</Switch>
</div>
)
}
};
export default Assignment;
Courses.js
import React, { Component } from 'react';
import {Link, Route} from 'react-router-dom';
import './Courses.css';
import Course from '../Course/Course';
class Courses extends Component {
state = {
courses: [
{ id: 1, title: 'Angular - The Complete Guide' },
{ id: 2, title: 'Vue - The Complete Guide' },
{ id: 3, title: 'PWA - The Complete Guide' }
]
}
render () {
return (
<div>
<h1>Amazing Udemy Courses</h1>
<section className="Courses">
{
this.state.courses.map( course => {
return (<Link key ={course.id} to = {this.props.match.url + '/' + course.id + '/' + course.title}>
<Course className = "Course" name = {course.title} no = {course.id} />
</Link>);
} )
}
<Route path = "/Courses/:id/:name" exact component = {Course} />
</section>
</div>
);
}
}
export default Courses;
Course.js
import React, { Component } from 'react';
class Course extends Component {
render () {
return (
<div>
<h1>{this.props.match.params.name}</h1>
<p>{this.props.match.params.id}_</p>
</div>
);
}
}
export default Course;
Why am I getting this error? Can anyone fix this? I am also finding it difficult to following dynamic routing.
PS. I am getting the error at /Courses url only not at the base url.
Have you tried withRouter?
import { withRouter } from 'react-router-dom';
console.log(props.match.params);
then export the component like:
export default withRouter(TestComponent);
Problems
The props such as params are only passed down to the top-level component which is rendered by a Route. When you are rendering the list of individual Course components inside your Course component, the Courses gets this.props.params but each Course does not. You can pass them down manually:
<Course {...this.props} className="Course" name={course.title} no={course.id} />
The above passes all props, while the below passes just the params prop.
<Course params={this.props.params} className="Course" name={course.title} no={course.id} />
This resolves your error, but it is not at all doing what you want it to be doing. The match is for the current URL, so this.props.match.params.name and this.props.match.params.id are both empty values when we are on the /Courses page. Meanwhile, the props className, name, and no which you set on the Course are all unused.
Additionally, the Route to "/Courses/:id/:name" which you have put inside of Courses should really be on the top level of the app alongside the main "/Courses" Route. Ideally it should be listed before the courses homepage route because you want to match to more specific paths before broader ones, but it won't present any conflicts with exact either way.
There is a lot wrong here and I recommend that you read up on the fundamentals of react-router and writing reusable components.
Rewrites
You are trying to use the same component to render a course for both your Route "/Courses/:id/:name" and as a list item on the Courses page, but one needs to have its data passed directly as props while the other gets its data from this.props.match.params. In order to solve this, we will make a component that handles just the rendering of the course. It gets its information from props, and is agnostic to where those props come from. This means we can use this component on any page of your app as long as we pass it a name and no. I used a function component, but it doesn't matter.
const CourseListItem = ({ name, no }) => {
return (
<div className="course">
<h1>{name}</h1>
<p>Course #{no}</p>
</div>
);
};
We can't send our Route directly to this component, because it wouldn't know the name and no. So we use an intermediate component that is responsible for setting the props of CourseListItem based on the router props (this.props.match.params). You could of course render other HTML or components and not just CourseListItem. I used a class for consistency with what you had before, but again it doesn't matter.
class SingleCoursePage extends Component {
render() {
return (
<CourseListItem
name={this.props.match.params.name}
no={this.props.match.params.id}
/>
);
}
}
In our Courses component, we loop through the courses from this.state and for each course we render the CourseListItem, setting the props name and no from the course object. See how we can use same component in different ways? If you wanted, you could make className be a prop of CourseListItem so that you could style it differently in different places.
class Courses extends Component {
state = {
courses: [
{ id: 1, title: "Angular - The Complete Guide" },
{ id: 2, title: "Vue - The Complete Guide" },
{ id: 3, title: "PWA - The Complete Guide" }
]
};
render() {
return (
<div>
<h1>Amazing Udemy Courses</h1>
<section className="Courses">
{this.state.courses.map((course) => {
return (
<Link
key={course.id}
to={"/Courses/" + course.id + "/" + course.title}
>
<CourseListItem name={course.title} no={course.id} />
</Link>
);
})}
</section>
</div>
);
}
}
As I explained, we are moving that Route for the single course page up to the top-level component, alongside the other routes.
class Assignment extends Component {
render() {
return (
<BrowserRouter>
<div>
<ul>
<li><Link to="/Users">Users</Link></li>
<li><Link to="/Courses">Courses</Link></li>
</ul>
<Switch>
<Route path="/Users" component={Users} />
<Route path="/Courses/:id/:name" component={SingleCoursePage} />
<Route path="/Courses" exact component={Courses} />
</Switch>
</div>
</BrowserRouter>
);
}
}
Code Sandbox Link - There's no CSS styling but all of the routing works!

Hitting Back button in React app doesn't reload the page

I have a React app (16.8.6) written in TypeScript that uses React Router (5.0.1) and MobX (5.9.4). The navigation works fine and data loads when it should, however, when I click the browser's Back button the URL changes but no state is updated and the page doesn't get re-rendered. I've read endless articles about this issue and about the withRouter fix, which I tried but it doesn't make a difference.
A typical use case is navigating to the summary page, selecting various things which cause new data to load and new history states to get pushed and then going back a couple of steps to where you started. Most of the history pushes occur within the summary component, which handles several routes. I have noticed that when going back from the summary page to the home page the re-rendering happens as it should.
My index.tsx
import { Provider } from 'mobx-react'
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorker from './serviceWorker'
import * as Utils from './utils/Utils'
const rootStore = Utils.createStores()
ReactDOM.render(
<Provider {...rootStore }>
<App />
</Provider>,
document.getElementById('root') as HTMLElement
)
serviceWorker.unregister()
My app.tsx
import * as React from 'react'
import { inject, observer } from 'mobx-react'
import { Route, Router, Switch } from 'react-router'
import Home from './pages/Home/Home'
import PackageSummary from './pages/PackageSummary/PackageSummary'
import ErrorPage from './pages/ErrorPage/ErrorPage'
import { STORE_ROUTER } from './constants/Constants'
import { RouterStore } from './stores/RouterStore'
#inject(STORE_ROUTER)
#observer
class App extends React.Component {
private routerStore = this.props[STORE_ROUTER] as RouterStore
public render() {
return (
<Router history={this.routerStore.history}>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/summary/:packageId" component={PackageSummary} />
<Route exact path="/summary/:packageId/:menuName" component={PackageSummary} />
<Route exact path="/summary/:packageId/:menuName/:appName" component={PackageSummary} />
<Route component={ErrorPage} />
</Switch>
</Router>
)
}
}
export default App
My router store
import { RouterStore as BaseRouterStore, syncHistoryWithStore } from 'mobx-react-router'
import { createBrowserHistory } from 'history'
export class RouterStore extends BaseRouterStore {
constructor() {
super()
this.history = syncHistoryWithStore(createBrowserHistory(), this)
}
}
How I create the MobX stores
export const createStores = () => {
const routerStore = new RouterStore()
const packageListStore = new PackageListStore()
const packageSummaryStore = new PackageSummaryStore()
const packageUploadStore = new PackageUploadStore()
return {
[STORE_ROUTER]: routerStore,
[STORE_SUPPORT_PACKAGE_LIST]: packageListStore,
[STORE_SUPPORT_PACKAGE_SUMMARY]: packageSummaryStore,
[STORE_SUPPORT_PACKAGE_UPLOAD]: packageUploadStore
}
}
So my questions are:
How can I get the page to load the proper data when the user goes back/forward via the browser?
If the solution is being able to get MobX to observe changes to the location, how would I do that?
You could implement something like this in your component:
import { inject, observer } from 'mobx-react';
import { observe } from 'mobx';
#inject('routerStore')
#observer
class PackageSummary extends React.Component {
listener = null;
componentDidMount() {
this.listener = observe(this.props.routerStore, 'location', ({ oldValue, newValue }) => {
if (!oldValue || oldValue.pathname !== newValue.pathname) {
// your logic
}
}, true)
}
componentWillUnmount() {
this.listener();
}
}
Problem with this approach is that if you go back from /summary to other page (e.g. '/'), callback will initiate, so you would also need some kind of check which route is this. Because of these kind of complications I would suggest using mobx-state-router, which I found much better to use with MobX.
React router monitors url changes and renders associated component defined for the route aka url.
You have to manually refresh or call a window function to reload.
If I remember correctly, using a browser back function does not reload the page (I might be wrong).
Why not try to detect the back action by a browser and reload the page when detected instead?
You can try the following code to manually reload the page when the browser back button is clicked.
$(window).bind("pageshow", function() {
// Run reload code here.
});
Also out of curiosity, why do you need so many different stores?
In App.js
useEffect(() => {
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload();
}
};
}, []);

Console.Log Not Being Called Inside React Constructor

I'm trying to add a component to a default .NET Core MVC with React project. I believe I have everything wired up to mirror the existing "Fetch Data" component, but it doesn't seem like it's actually being called (but the link to the component in my navbar does move to a new page).
The component itself...
import React, { Component } from 'react';
export class TestComponent extends Component {
static displayName = TestComponent.name;
constructor (props) {
super(props);
console.log("WHO NOW?");
this.state = { message: '', loading: true, promise: null };
this.state.promise = fetch('api/SampleData/ManyHotDogs');
console.log(this.state.promise);
}
static renderForecastsTable (message) {
return (
<h1>
Current Message: {message}
</h1>
);
}
render () {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: TestComponent.renderForecastsTable(this.state.message);
return (
<div>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
{contents}
</div>
);
}
}
The App.js
import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { TestComponent } from './components/TestComponent';
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetch-data' component={FetchData} />
<Route path='/test-controller' component={TestComponent} />
</Layout>
);
}
}
That console.log("Who now") is never called when I inspect, and the page remains totally blank. I can't find a key difference between this and the functioning components, and google has not been much help either. Any ideas what is missing?
Edit
While troubleshooting this, I ended up creating a dependency nightmare that broke the app. Since I'm only using the app to explore React, I nuked it and started over--and on the second attempt I have not been able to reproduce the not-rendering issue.
It is advisable to use componentDidMount to make the call to the REST API with the fetch or axios.
class TestComponent extends Component{
constructor(props){
state = {promise: ''}
}
async componentDidMount () {
let promise = await fetch ('api / SampleData / ManyHotDogs');
this.setState ({promise});
console.log (promise);
}
render(){
return(
<div>{this.state.promise}</div>
);
}
}

Categories

Resources