React Query String showing 404 when provided with query parameter - javascript

I am new to React and trying to render a page based on the name query like
http://localhost:3000/show?name=james
So I initially added the Route as :
<BrowserRouter>
<Switch>
<Route path='*' component={ErrorComponent} />} />
<Route path="show(/:name)" name="name" component={Show}></Route>
</Switch>
</BrowserRouter>
And then I tried to render the component Show like below:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const { params } = this.props.match;
return <div>
<h4>About</h4>
<p>This is About page.</p>
{params.id ? <b>ID: {params.id}</b> : <i>ID is optional.</i>}
</div>
}
}
export default Show;
then when I try to show the page
http://localhost:3000/show?name=james
It always show 404. Not sure which part I am doing it wrong. Any help is appreciated.
Also I am using react-router-dom 5.1.2 .
Thanks.

path="show(/:name)"
This isn't a valid URL path to match on.
Redefine the path to ["/show/:id", "/show"]
<Route path={["/show/:id", "/show"]} name="name" component={Show} />
And since the Route is directly rendering the component, it can pull the query parameters and match parameters straight from props (this.props.match.params & this.props.location.search). Specifying two matching paths is equivalent to defining two separate Routes that render the same component. The same rules apply to path specificity, so define more complex matches first within the array.
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const { params } = this.props.match;
return <div>
<h4>About</h4>
<p>This is About page.</p>
{params.id ? <b>ID: {params.id}</b> : <i>ID is optional.</i>}
</div>
}
}

EDIT: Can't believe I didn't notice this originally...
You need to put your path="*" route at the bottom of the Switch otherwise it'll match everything and anything below it won't even have a chance to match since Switches match only a single route. The description of making sure you have your route path set up correctly (below) is applicable as well, of course.
<Switch>
<Route path="/show/:name?" component={ShowRouteParam} />
<Route path="*">ERROR 404</Route>
</Switch>
https://codesandbox.io/s/elated-browser-d0sew?file=/src/App.js
The routes don't match query parameters.
"Please note: The RegExp returned by path-to-regexp is intended for
use with pathnames or hostnames. It can not handle the query strings
or fragments of a URL."
Depending on how you want to do it, you can either make the id an optional part of the route, or let it be a normal query parameters
Option 1:
<Route path="/show/:name?" component={Show}></Route>
component:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const { params } = this.props.match;
return <div>
<h4>About</h4>
<p>This is About page.</p>
{params.name ? <b>ID: {params.name}</b> : <i>Name is optional.</i>}
</div>
}
}
export default Show;
Option 2:
<Route path="/show" component={Show}></Route>
component:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const values = queryString.parse(this.props.location.search);
return <div>
<h4>About</h4>
<p>This is About page.</p>
{values.name ? <b>ID: {values.name}</b> : <i>Name is optional.</i>}
</div>
}
}
export default Show;
Working example: https://codesandbox.io/s/silent-rain-n61zs

Related

Uncaught TypeError: match is undefined

import books from '../books'
function BookScreen({ match }) {
const book = books.find((b) => b._id === match.params.id)
return (
<div>
{book}
</div>
)
}
export default BookScreen
I keep getting the error match is undefined. I saw a tutorial with similar code, but it seemed fine when put to the test. Any clue what might be the issue?
If match prop is undefined this could be from a few things.
react-router-dom v5
If using RRDv5 if the match prop is undefined this means that BookScreen isn't receiving the route props that are injected when a component is rendered on the Route component's component prop, or the render or children prop functions. Note that using children the route will match and render regardless, see route render methods for details.
Ensure that one of the following is implemented to access the match object:
Render BookScreen on the component prop of a Route
<Route path="...." component={BookScreen} />
Render BookScreen on the render or children prop function of a Route and pass the route props through
<Route path="...." render={props => <BookScreen {...props} />} />
or
<Route path="...." children={props => <BookScreen {...props} />} />
Decorate BookScreen with the withRouter Higher Order Component to have the route props injected
import { withRouter } from 'react-router-dom';
function BookScreen = ({ match }) {
const book = books.find((b) => b._id === match.params.id)
return (
<div>
{book}
</div>
);
};
export default withRouter(BookScreen);
Since BookScreen is a React function component, import and use the useParams hook to access the route match params
import { useParams } from 'react-router-dom';
...
function BookScreen() {
const { id } = useParams();
const book = books.find((b) => b._id === id)
return (
<div>
{book}
</div>
);
}
react-router-dom v6
If using RRDv6 then there is no match prop. Gone are the route props. Here only the useParams and other hooks exist, so use them.
import { useParams } from 'react-router-dom';
...
function BookScreen() {
const { id } = useParams();
const book = books.find((b) => b._id === id)
return (
<div>
{book}
</div>
);
}
If you've other class components and you're using RRDv6 and you don't want to convert them to function components, then you'll need to create a custom withRouter component. See my answer here with details.
I guess you rendered BookScreen component before match is initialized. This is why match is undefined when BookScreen rendered. Render it conditionally like below.
return (
... other components
{match && <BookScreen match={match}/>}
)
Also, I leave useful site which tells you some good ways to do that. :D
https://www.digitalocean.com/community/tutorials/7-ways-to-implement-conditional-rendering-in-react-applications
I hope you find an answer :D

How to call a Component which name is passed as props in React?

i'm new at React. Basically i want to call different components based on the string passed as props. I've component named Device that have as prop the name of a particular device and in Device i want to call another components which has as name the props. Something like this: <DeviceName/>
This is my code:
App.js
<Device name = {devName} />
Device.js
import DeviceMark from ./devices/DeviceMark
function DeviceName({devName}) {
const DevName = devName;
return (
<Router>
<Switch>
<Route path = "/" exact><DevName /></Route>
</Switch>
</Router>
)
}
Imagine that in this case DevName will replace DeviceMark
When you really need to convert string component names to actual components while rendering, I can suggest following way
import DeviceMark from ./devices/DeviceMark
function DeviceName({devName}) {
const mappingComponents = {
foo: FooComponent,
bar: BarComponent,
deviceMark: DeviceMark
};
const ComponentToRender = mappingComponents[devName || 'foo'];
return (
<Router>
<Switch>
<Route path = "/" exact><ComponentToRender></ComponentToRender></Route>
</Switch>
</Router>
)
}
More details in official doc - https://reactjs.org/docs/jsx-in-depth.html
I guess you need to use React.createElement. It allows to create React element from string (if it's a basic html tag) or from function (if it's a React component).
import React from 'react'
import ReactDOM from 'react-dom'
const DeviceName = () => {
return 'sub component'
}
const Device = ({subDev}) => {
return (
<div>
{ React.createElement(subDev) }
</div>
)
}
function App() {
return <Device subDev={DeviceName} />
}
ReactDOM.render(<App />, document.getElementById('root'))
It's a little example. I have a main component Device. It accepts a sub-component via a prop and I pass sub-component to createElement. It does not matter if sub-component whether basic html tag or React component.
It's codesandbox example.

React Routing to Same Component with Different URL

In my main class I have a nav bar with the options below:
<NavDropdown title="Search" id="collasible-nav-dropdown">
<NavDropdown.Item href="#/searchpage/p" onClick={this.dontEdit}>Find People</NavDropdown.Item>
<NavDropdown.Item href="#/searchpage/s" onClick={this.searchSchool}>Find Schools</NavDropdown.Item>
<NavDropdown.Item href="#/searchpage/w" onClick={this.dontEdit}>Find Work Places</NavDropdown.Item>
</NavDropdown>
These have a route which routes to the same component which then reads the parameter at the end of the URL and runs a different search depending on the value. For example 's' is search schools and 'p' is search people. If I navigate between the different search functions from the nav bar then it doesn't refresh to the new search. For example if I go from 'Find Schools' to 'Find Work' it stays on schools, but if I were to go direct to 'Find Work Places' then it goes there direct. Also if I navigate to the home page and back to another search then it works.
The route looks like:
<Route path="/searchpage/:type" render={props => (<SearchPage {...props} findPerson={this.findPerson} routeReset={this.routeReset} getPersonsByName={this.getPersonsByName} />)}/>
Is anyone able to advise how to get this to route as I want it to? The search component is like:
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
import Flash from './components/flash';
import Search from "./components/search";
const searchtypes = {"p":"People","w":"Work Places","s":"Schools"};
class SearchPage extends Component {
constructor(props) {
super(props);
this.state = {
type:this.props.match.params.type
}
}
componentDidMount(){
}
render() {
return (
<Container>
<Row>
<Col>
<h4>Search {searchtypes[this.state.type]}</h4>
<br/>
</Col>
</Row>
<Row><Col><Search {...this.props} type={this.state.type}/></Col></Row>
</Container>
);
}
}
export default SearchPage;
The Route's render prop doesn't remount when the matched route doesn't change, i.e. even when the route matches but the route param is different it won't re-render. Instead use the component prop.
react-router-dom component
When you use component (instead of render or children, below) the
router uses React.createElement to create a new React element from the
given component. That means if you provide an inline function to the
component prop, you would create a new component every render. This
results in the existing component unmounting and the new component
mounting instead of just updating the existing component. When using
an inline function for inline rendering, use the render or the
children prop (below).
<Route
path="/searchpage/:type"
component={props => (
<SearchPage
{...props}
findPerson={this.findPerson}
routeReset={this.routeReset}
getPersonsByName={this.getPersonsByName}
/>
)}
/>
An alternative to this is to implement the componentDidUpdate lifecycle function in SearchPage to detect when the route param prop updates and update the type stored in state. This way the component won't continually unmount/mount each time.
componentDidUpdate(prevProps) {
if (prevProps.match.params.type !== this.props.match.params.type) {
setState({
type: this.props.match.params.type,
});
}
}
Try this:
class SearchPage extends Component {
render() {
return (
<Container>
<Row>
<Col>
<h4>Search {searchtypes[this.props.match.params.type]}</h4>
<br/>
</Col>
</Row>
<Row><Col><Search {...this.props} type={this.props.match.params.type}/></Col></Row>
</Container>
);
}
}
The type data comes from props and therefore you should not persist it on the component state.
Note: Make sure you use react-router Link component it seems you use native a tags

React pass object by routing?

What I want to do is set routing to my object. For example:
I set routing for:
http://localhost:3000/projects
It displays all my projects list (it works pretty ok)
Then I want to choose project and see details, but it doesn't work properly:
http://localhost:3000/projects/3
How it looks like:
When I click to Details button, it sends me to /projects:id but I get an error, that items in project are undefined.
My code. I store all routing in main App.js file:
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<div>
<Route exact path="/projects" component={ProjectsList} />
<Route exact path="/projects/:id" component={ProjectDetails} />
</div>
</BrowserRouter>
</div>
);
}
}
export default App;
I have ProjectsList.js component (i will include code of it if needed), in ProjectsList.js i have listgroup with Project.js that looks like this:
class Project extends Component {
render() {
return (
<ButtonToolbar>
<ListGroupItem>{this.props.project.name</ListGroupItem>
<Link to={`/projects/${this.props.project.id}`}>
<Button>Details</Button>
</Link>
</ButtonToolbar>
);
}
}
export default Project;
By Link to my browser pass me to proper URL (projects/2... etc) but i dont know how to pass object of project to ProjectDetails.js component. Code of it below:
class ProjectDetails extends Component {
render() {
return <li>{this.props.project.description}</li>;
}
}
export default ProjectDetails;
Could you tell me, how to pass object of project by Link to into ProjectDetails.js? For now, i get description as undefined (its obviouse because i pass nothing to component with details).
Use the render method in your route and pass the props.
<Route exact path="/projects/:id" render={() => (
<ProjectDetails
project = {project}
/>
)}/>
You need to use mapStateToProps here. and wrap your component in the conncet from react-redux.
It should be like:
import {connect} from 'react-redux';
class ProjectDetails extends Component {
render() {
return <li>{this.props.project.description}</li>;
}
}
function mapStateToProps(state, ownProps){
const projectInstance = DATA //the Data you are getting or fetching from the ID.
return { project : projectInstance }
}
export default connect((mapStateToProps)(ProjectDetails))
This is what it will look like..!!
class Project extends Component {
render() {
return (
<ButtonToolbar>
<ListGroupItem>{this.props.project.name</ListGroupItem>
<Link to={`/projects/${this.props.project.id}`}>
<Button>Details</Button>
</Link>
</ButtonToolbar>
);
}
}
function mapStateToProps(state, ownProps){
return { project : { id: ownProps.params.id } }
}
export default connect((mapStateToProps)(Project))

React Router v4 Nested match params not accessible at root level

Test Case
https://codesandbox.io/s/rr00y9w2wm
Steps to reproduce
Click on Topics
Click on Rendering with React
OR
Go to https://rr00y9w2wm.codesandbox.io/topics/rendering
Expected Behavior
match.params.topicId should be identical from both the parent Topics component should be the same as match.params.topicId when accessed within the Topic component
Actual Behavior
match.params.topicId when accessed within the Topic component is undefined
match.params.topicId when accessed within the Topics component is rendering
I understand from this closed issue that this is not necessarily a bug.
This requirement is super common among users who want to create a run in the mill web application where a component Topics at a parent level needs to access the match.params.paramId where paramId is a URL param that matches a nested (child) component Topic:
const Topic = ({ match }) => (
<div>
<h2>Topic ID param from Topic Components</h2>
<h3>{match.params.topicId}</h3>
</div>
);
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<h3>{match.params.topicId || "undefined"}</h3>
<Route path={`${match.url}/:topicId`} component={Topic} />
...
</div>
);
In a generic sense, Topics could be a Drawer or Navigation Menu component and Topic could be any child component, like it is in the application I'm developing. The child component has it's own :topicId param which has it's own (let's say) <Route path="sections/:sectionId" component={Section} /> Route/Component.
Even more painful, the Navigation Menu needn't have a one-to-one relationship with the component tree. Sometimes the items at the root level of the menu (say Topics, Sections etc.) might correspond to a nested structure (Sections is only rendered under a Topic, /topics/:topicId/sections/:sectionId though it has its own normalized list that is available to the user under the title Sections in the Navigation Bar).
Therefore, when Sections is clicked, it should be highlighted, and not both Sections and Topics.
With the sectionId or sections path unavailable to the Navigation Bar component which is at the Root level of the application, it becomes necessary to write hacks like this for such a commonplace use case.
I am not an expert at all at React Router, so if anyone can venture a proper elegant solution to this use case, I would consider this to be a fruitful endeavor. And by elegant, I mean
Uses match and not history.location.pathname
Does not involve hacky approaches like manually parsing the window.location.xxx
Doesn't use this.props.location.pathname
Does not use third party libraries like path-to-regexp
Does not use query params
Other hacks/partial solutions/related questions:
React Router v4 - How to get current route?
React Router v4 global no match to nested route childs
TIA!
React-router doesn't give you the match params of any of the matched children Route , rather it gives you the params based on the current match. So if you have your Routes setup like
<Route path='/topic' component={Topics} />
and in Topics component you have a Route like
<Route path=`${match.url}/:topicId` component={Topic} />
Now if your url is /topic/topic1 which matched the inner Route but for the Topics component, the matched Route is still, /topic and hence has no params in it, which makes sense.
If you want to fetch params of the children Route matched in the topics component, you would need to make use of matchPath utility provided by React-router and test against the child route whose params you want to obtain
import { matchPath } from 'react-router'
render(){
const {users, flags, location } = this.props;
const match = matchPath(location.pathname, {
path: '/topic/:topicId',
exact: true,
strict: false
})
if(match) {
console.log(match.params.topicId);
}
return (
<div>
<Route exact path="/topic/:topicId" component={Topic} />
</div>
)
}
EDIT:
One method to get all the params at any level is to make use of context and update the params as and when they match in the context Provider.
You would need to create a wrapper around Route for it to work correctly, A typical example would look like
RouteWrapper.jsx
import React from "react";
import _ from "lodash";
import { matchPath } from "react-router-dom";
import { ParamContext } from "./ParamsContext";
import { withRouter, Route } from "react-router-dom";
class CustomRoute extends React.Component {
getMatchParams = props => {
const { location, path, exact, strict } = props || this.props;
const match = matchPath(location.pathname, {
path,
exact,
strict
});
if (match) {
console.log(match.params);
return match.params;
}
return {};
};
componentDidMount() {
const { updateParams } = this.props;
updateParams(this.getMatchParams());
}
componentDidUpdate(prevProps) {
const { updateParams, match } = this.props;
const currentParams = this.getMatchParams();
const prevParams = this.getMatchParams(prevProps);
if (!_.isEqual(currentParams, prevParams)) {
updateParams(match.params);
}
}
componentWillUnmount() {
const { updateParams } = this.props;
const matchParams = this.getMatchParams();
Object.keys(matchParams).forEach(k => (matchParams[k] = undefined));
updateParams(matchParams);
}
render() {
return <Route {...this.props} />;
}
}
const RouteWithRouter = withRouter(CustomRoute);
export default props => (
<ParamContext.Consumer>
{({ updateParams }) => {
return <RouteWithRouter updateParams={updateParams} {...props} />;
}}
</ParamContext.Consumer>
);
ParamsProvider.jsx
import React from "react";
import { ParamContext } from "./ParamsContext";
export default class ParamsProvider extends React.Component {
state = {
allParams: {}
};
updateParams = params => {
console.log({ params: JSON.stringify(params) });
this.setState(prevProps => ({
allParams: {
...prevProps.allParams,
...params
}
}));
};
render() {
return (
<ParamContext.Provider
value={{
allParams: this.state.allParams,
updateParams: this.updateParams
}}
>
{this.props.children}
</ParamContext.Provider>
);
}
}
Index.js
ReactDOM.render(
<BrowserRouter>
<ParamsProvider>
<App />
</ParamsProvider>
</BrowserRouter>,
document.getElementById("root")
);
Working DEMO
Try utilizing query parameters ? to allow the parent and child to access the current selected topic. Unfortunately, you will need to use the module qs because react-router-dom doesn't automatically parse queries (react-router v3 does).
Working example: https://codesandbox.io/s/my1ljx40r9
URL is structured like a concatenated string:
topic?topic=props-v-state
Then you would add to the query with &:
/topics/topic?topic=optimization&category=pure-components&subcategory=shouldComponentUpdate
✔ Uses match for Route URL handling
✔ Doesn't use this.props.location.pathname (uses this.props.location.search)
✔ Uses qs to parse location.search
✔ Does not involve hacky approaches
Topics.js
import React from "react";
import { Link, Route } from "react-router-dom";
import qs from "qs";
import Topic from "./Topic";
export default ({ match, location }) => {
const { topic } = qs.parse(location.search, {
ignoreQueryPrefix: true
});
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/topic?topic=rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/topic?topic=components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/topic?topic=props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<h2>
Topic ID param from Topic<strong>s</strong> Components
</h2>
<h3>{topic && topic}</h3>
<Route
path={`${match.url}/:topicId`}
render={props => <Topic {...props} topic={topic} />}
/>
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
};
Another approach would be to create a HOC that stores params to state and children update the parent's state when its params have changed.
URL is structured like a folder tree: /topics/rendering/optimization/pure-components/shouldComponentUpdate
Working example: https://codesandbox.io/s/9joknpm9jy
✔ Uses match for Route URL handling
✔ Doesn't use this.props.location.pathname
✔ Uses lodash for object to object comparison
✔ Does not involve hacky approaches
Topics.js
import map from "lodash/map";
import React, { Fragment, Component } from "react";
import NestedRoutes from "./NestedRoutes";
import Links from "./Links";
import createPath from "./createPath";
export default class Topics extends Component {
state = {
params: "",
paths: []
};
componentDidMount = () => {
const urlPaths = [
this.props.match.url,
":topicId",
":subcategory",
":item",
":lifecycles"
];
this.setState({ paths: createPath(urlPaths) });
};
handleUrlChange = params => this.setState({ params });
showParams = params =>
!params
? null
: map(params, name => <Fragment key={name}>{name} </Fragment>);
render = () => (
<div>
<h2>Topics</h2>
<Links match={this.props.match} />
<h2>
Topic ID param from Topic<strong>s</strong> Components
</h2>
<h3>{this.state.params && this.showParams(this.state.params)}</h3>
<NestedRoutes
handleUrlChange={this.handleUrlChange}
match={this.props.match}
paths={this.state.paths}
showParams={this.showParams}
/>
</div>
);
}
NestedRoutes.js
import map from "lodash/map";
import React, { Fragment } from "react";
import { Route } from "react-router-dom";
import Topic from "./Topic";
export default ({ handleUrlChange, match, paths, showParams }) => (
<Fragment>
{map(paths, path => (
<Route
exact
key={path}
path={path}
render={props => (
<Topic
{...props}
handleUrlChange={handleUrlChange}
showParams={showParams}
/>
)}
/>
))}
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</Fragment>
);
If you have a known set of child routes then you can use something like this:
Import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'
<Router>
<Route path={`${baseUrl}/home/:expectedTag?/:expectedEvent?`} component={Parent} />
</Router>
const Parent = (props) => {
return (
<div >
<Switch>
<Route path={`${baseUrl}/home/summary`} component={ChildOne} />
<Route
path={`${baseUrl}/home/:activeTag/:activeEvent?/:activeIndex?`}
component={ChildTwo}
/>
</Switch>
<div>
)
}
In the above example Parent will get expectedTag, expectedEvent as the match params and there is no conflict with the child components and Child component will get activeTag, activeEvent, activeIndex as the parameters. Same name for params can also be used, I have tried that as well.
Try to do something like this:
<Switch>
<Route path="/auth/login/:token" render={props => <Login {...this.props} {...props}/>}/>
<Route path="/auth/login" component={Login}/>
First, the route with the parameter and after the link without parameter.
Inside my Login component I put this line of code console.log(props.match.params.token); to test and worked for me.
If you happen to use React.FC, there is a hook useRouteMatch.
For instance, parent component routes:
<div className="office-wrapper">
<div className="some-parent-stuff">
...
</div>
<div className="child-routes-wrapper">
<Switch>
<Route exact path={`/office`} component={List} />
<Route exact path={`/office/:id`} component={Alter} />
</Switch>
</div>
</div>
And in your child component:
...
import { useRouteMatch } from "react-router-dom"
...
export const Alter = (props) => {
const match = useRouteMatch()
const officeId = +match.params.id
//... rest function code
}

Categories