Getting undefined components in React Router v4 - javascript

Just upgraded to react-router-dom 4.0.0. All my components are either regular classes or fat arrows. They are all exported using export default ThatComponent. Yet I'm getting this:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of Router.
// minimal showcase
import { BrowserRouter, Match, Miss } from 'react-router';
const Router = () => (
<BrowserRouter>
<div>
{/* both Match and Miss components below cause an error */}
<Match exactly pattern="/login" component={Login} />
<Match exactly pattern="/frontpage" component={Frontpage} />
<Match exactly pattern="/logout" render={() => (<div>logout</div>)} />
<Miss component={NoMatch} />
</div>
</BrowserRouter>
);
Why do the <Match> components think the other components are undefined?

In the final release of react-router there is no Match nor Miss. You just need to use Route. Also, you need to install and import react-router-dom package to use BrowserRouter (see React Router documentation).
To make your example work with minimal changes, you'd need to do the following:
// minimal showcase
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const Router = () => (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/frontpage" component={Frontpage} />
<Route exact path="/logout" render={() => (<div>logout</div>)} />
<Route component={NoMatch} />
</Switch>
</BrowserRouter>
);
Please have a look at NoMatchExample in React Router docs to see how to and when to use Switch.

Check source of react-router here: https://unpkg.com/react-router#4.0.0/index.js(also https://unpkg.com/react-router-dom#4.0.0/index.js),
There is no Match under it. Match maybe belong to other package.

Related

How should I return HTML in a React.js class component without getting an error? [duplicate]

Matched leaf route at location "/" does not have an element. This means it will render an with a null value by default resulting in an "empty" page
//App.js File
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
// import ReactDOM from "react-dom";
const App = () => {
return (
<Router >
<Routes>
<Route path="/" component={ Home }></Route>
</Routes>
</Router>
)
}
export default App;
**My any react router related code not working i don't know why it happend when i start insert some route in program so it show this error **
In V6, you can't use the component prop anymore. It was replaced in favor of element:
<Route path="/" element={<Home />}></Route>
More info in the migration doc.
I had the same problem. Replace component with element and it worked.
Replace this:
<Route path="/" component={HomePage} exact />
with this:
<Route path="/" element={<HomePage/>} exact />
I had the same error however my fix was slightly different
I had spelled element wrong.
<Route exact path='/MyGames' elemtent={<MyGames/>}/>
and this was the error it gave me in the browser console
Matched leaf route at location "/MyGames" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Very simple:
use element instead of component
wrap the your component like this: {<Home/>} instead of {Home}
<Route path="/" component={ <Home/> } />
in version 6:
component replaced with element and needs to close "</Route>"
<Route exact path="/" element={<AddTutorial />}></Route>
https://reactrouter.com/docs/en/v6/getting-started/overview
This is a common problem if you are using react-router-dom V6
To solve this it's simple
In your code
Replace component with element
Replace {home} with {}
This becomes...
<Route path="/" element={}>
This will definitely solve the problem.
If you're using react-router-dom 6 or above, you may have a routes array that includes parent and child routes. You may then try to open a route such as
/portal
and get this error because that component corresponds to a child route
/:customerid/portal
but you haven't read your routes (and their child routes) closely enough to see that.

Matched leaf route at location "/" does not have an element

Matched leaf route at location "/" does not have an element. This means it will render an with a null value by default resulting in an "empty" page
//App.js File
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
// import ReactDOM from "react-dom";
const App = () => {
return (
<Router >
<Routes>
<Route path="/" component={ Home }></Route>
</Routes>
</Router>
)
}
export default App;
**My any react router related code not working i don't know why it happend when i start insert some route in program so it show this error **
In V6, you can't use the component prop anymore. It was replaced in favor of element:
<Route path="/" element={<Home />}></Route>
More info in the migration doc.
I had the same problem. Replace component with element and it worked.
Replace this:
<Route path="/" component={HomePage} exact />
with this:
<Route path="/" element={<HomePage/>} exact />
I had the same error however my fix was slightly different
I had spelled element wrong.
<Route exact path='/MyGames' elemtent={<MyGames/>}/>
and this was the error it gave me in the browser console
Matched leaf route at location "/MyGames" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Very simple:
use element instead of component
wrap the your component like this: {<Home/>} instead of {Home}
<Route path="/" component={ <Home/> } />
in version 6:
component replaced with element and needs to close "</Route>"
<Route exact path="/" element={<AddTutorial />}></Route>
https://reactrouter.com/docs/en/v6/getting-started/overview
This is a common problem if you are using react-router-dom V6
To solve this it's simple
In your code
Replace component with element
Replace {home} with {}
This becomes...
<Route path="/" element={}>
This will definitely solve the problem.
If you're using react-router-dom 6 or above, you may have a routes array that includes parent and child routes. You may then try to open a route such as
/portal
and get this error because that component corresponds to a child route
/:customerid/portal
but you haven't read your routes (and their child routes) closely enough to see that.

ReactDOM.render inside index.js does not render my app and instead throws this error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of Context.Consumer.
But the thing is I'm not using Context in my app, and the console of Visual Studio does not read any errors.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import App from './Components/App.js';
const container = document.getElementById('root')
ReactDOM.render(<App />, container)
App.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Inicio from '../Pages/Inicio.js'
import Adopcion from '../Pages/Adopcion.js'
import NotFound from '../Components/NotFound.js'
const App = () => (
<BrowserRouter>
<Switch>
<Route exact path='/inicio' component={<Inicio />}/>
<Route exact path='/inicio/adoptar' component={<Adopcion />}/>
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
export default App;
I spent all afternoon reading about Context, going back to the React documentation, but I don't know how to tell React to render my app. Thank you for answering.
Your mistake is in your route declarations, specifically:
component={<Inicio />}
and
component={<Adopcion />}
What you're doing there is that you create instances, i.e. objects, of Inicio and Adopcion and passing those objects as the component prop to the route. As the error message says, it expects a function/class so you need to pass in the actual components, the same way you do with the NotFound route:
<Route exact path='/inicio' component={Inicio}/>
<Route exact path='/inicio/adoptar' component={Adopcion}/>
<Route component={NotFound} />
The reason the error message mentions Context.Consumer is because that's what react-router uses internally to render your components and react-router doesn't validate what you passed in, it just passes it through.

Invariant Violation: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

I'm working swith React and Webpack on a server side rendering App. When open my localhost page the page render this error :
[[AWarning: React.createElement: type is invalid -- expected a string
(for built-in components) or a class/function (for composite
components) but got: undefined. You likely forgot to export your
component from the file it's defined in, or you might have mixed up
default and named imports.
However my importation is good and don't know why the server returns me this error.
Here my App.js :
const AppRoute = () => {
if(process.env.BROWSER){
return <Provider store={store}>
<BrowserRouter history={ history }>
<Switch>
<Route path="/" component={App} exact />
<Route path="/post_entry" component={postEntry} exact />
</Switch>
</BrowserRouter>
</Provider>
}
else {
return
<Provider store={store}>
<ServerRouter history={ history }>
<Switch>
<Route path="/" component={App} exact />
<Route path="/post_entry" component={postEntry} exact />
</Switch>
</ServerRouter>
</Provider>
}
}
export default AppRoute // great default export
my server.js :
import AppRoute from "../app/Router"; // great default import
<body>
<div id="root">${renderToString(<AppRoute/>)}</div>
</body>
my browser.js :
import {render} from "react-dom" ;
import AppRoute from "../app/Router"; // great default import
render( <AppRoute/> {...} )
I can't figure out what is wrong, if somebody got any hint would be good,
Thanks

<Switch> component matching null value in react-router-4

I'm trying to migrate to use React Router 4 and having some trouble understanding the logic of the <Switch> component as it's used in the docs to handle a 404 (or unmatched) route.
For my entry JavaScript file, I have the following routes set up.
index.js
<Switch>
<Route path="/login" component={Login} />
<Route path="/forgot-password" component={ForgotPassword} />
<Route path="/email-verification" component={EmailVerification} />
<Route component={App} />
</Switch>
The Login component will check to see if the user is authenticated, and if so, redirect the user to the /dashboard route (via history.replace).
The App component is only accessible when the user is authenticated and it has a similar check to redirect the user to /login if she is not.
In my App component I have more specified routes that I can be sure are only accessible if the user is logged in.
App.js
<Switch>
<Route path="/dashboard" component={Dashboard} />
<Route path="/accounts" component={Account} />
<Authorize permissions={['view-admin']}>
<Route path="/admin" component={Admin} />
</Authorize>
<Route path="/users" component={Users} />
<Route component={NotFound} />
</Switch>
Herein lies my problem. The Authorize component checks against the permissions passed to see if the user has those permissions, if so, it renders the children directly, if not, it returns null from render().
The expected behavior here is that the <Route path="/admin" /> does not render at all when there are insufficient permissions and the <Route component={NotFound} /> component renders.
According to the docs:
A renders the first child that matches. A
with no path always matches.
However, if I go to any route declared after the <Authorize> component, the router is matching to null. This means that, based on the example above, going to /users returns null. Is the expected behavior of react-router to return the first match in a <Switch/> component, even if it's a null value?
How can I provide a "catch-all" route (404) for such a situation without creating a <PrivateRoute> component for each of the many, authenticated routes in App.js? Should a null value really produce a match?
Unfortunately, react-router's Switch component won't work with routes nested inside other components like in your example. If you check the docs for Switch, it says:
All children of a <Switch> should be <Route> or <Redirect> elements.
... so your Authorize component is not actually legal there as a direct child of Switch.
If you have a read through the source code of the Switch component, you'll see that it rather evilly reads the props of each of its children and manually applies react-router's matchPath method on each child's path (or from) prop to determine which one should be rendered.
So, what's happening in your case is Switch iterates through its children until it gets to your Authorize component. It then looks at that component's props, finding neither a path or from prop, and calls matchPath on an undefined path. As you note yourself, "a <Route> with no path always matches", so matchPath returns true, and Switch renders your Authorize component (ignoring any subsequent Routes or Redirects, since it believes it found a match). The nested '/admin' route inside your Authorize component doesn't match the current path however, so you get a null result back from the render.
I'm facing a similar situation at work. My plan to work around it is to replace react-router's Switch in my routing code with a custom component which iterates through its children, manually rendering each one in turn, and returning the result of the first one that returns something other than null. I'll update this answer when I've given it a shot.
Edit: Well, that didn't work. I couldn't work out a supported way to manually invoke "render" on the children. Sorry I couldn't give you a workaround to Switch's limitations.
In case anyone reads this in >= 2019, one way to deal with this behaviour is to simply wrap the Route-component like so:
import React from 'react'
import { Route } from 'react-router-dom'
type Props = {
permissions: string[]
componentWhenNotAuthorized?: React.ElementType
}
const AuthorizedRoute: React.FunctionComponent<Props> = ({
permissions,
componentWhenNotAuthorized: ComponentWhenNotAuthorized,
...rest
}) => {
const isAuthorized = someFancyAuthorizationLogic(permissions)
return isAuthorized
? <Route {...rest} />
: ComponentWhenNotAuthorized
? <ComponentWhenNotAuthorized {...rest} />
: null
}
export default AuthorizedRoute
Then, simply use it as such:
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import AuthorizedRoute from 'some/path/AuthorizedRoute'
import Account from 'some/path/Account'
import Admin from 'some/path/Admin'
import Dashboard from 'some/path/Dashboard'
import NotFound from 'some/path/NotFound'
import Users from 'some/path/Users'
const AppRouter: React.FunctionComponent = () => (
<Switch>
<Route
component={Account}
path='/accounts'
/>
<AuthorizedRoute
component={Admin}
componentWhenNotAuthorized={NotFound}
path='/admin'
permissions={['view-admin']}
/>
<Route
component={Dashboard}
path='/dashboard'
/>
<Route
component={Users}
path='/users'
/>
<Route
component={NotFound}
/>
</Switch>
)
export default AppRouter
Similar idea to what Robert said, here's how I did it
class NullComponent extends React.Component {
shouldComponentBeRenderedByRoute() {
return false;
}
render() {
return null;
}
}
class CustomSwitch extends React.Component {
render() {
return (
// React.Children.map returns components even for null, which
const children = React.Children.toArray(this.props.children).map(child => {
const { render, shouldComponentBeRenderedByRoute } = child.type.prototype;
if (shouldComponentBeRenderedByRoute && !shouldComponentBeRenderedByRoute.call(child)) {
return null;
}
if (shouldComponentBeRenderedByRoute) {
return render.call(child);
}
return child;
});
return <Switch>{children}</Switch>;
);
}
}
then use it just do
<CustomSwitch>
<Route path... />
<NullComponent />
<Route path... />
</CustomSwitch>
here, a component without shouldComponentBeRenderedByRoute function is assumed to be a valid Route component from react-router, but you can add more condition (maybe use path props) to check if it's a valid Route

Categories