I'm trying to pass parameter to component using URL.I'm using react component not functionnel component so I can't use hooks? How can I read url parameter in class component ? I'm trying to pass parameter to a component so it can depending on parameter fetch data from database and update it or just create a new record! Thanks
3 Answers
You can use the withRouter HOC decorator. This decorates a component (either class-based or functional) and injects match, location, and history props.
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
The match prop is the one that allows you to access the URL params
this.props.match.params
6 Comments
Marwane Hcine
I'm getting × TypeError: Cannot read property 'params' of undefined
Drew Reese
@MarwaneHcine Did you decorate your component? If you are having trouble you can always update your question to include actual code and we can better guide/direct you. A good example code snippet would be your entire component code and your router so we can see how routes are configured and what URL parameters you have.
Marwane Hcine
Thanks !. Im simply trying to render a component with parameter, depending in the parameter the user will create a new record in database or fetch old record and update it!
Marwane Hcine
I keep getting this error :'You should not use <Route> or withRouter() outside a <Router>'
Drew Reese
Yes, somewhere near the root of your app should be a router, wrapping the bulk of your app. This really would be much easier or faster if you shared your code, without it no one can point out what and where you may have issues.
|
You can send match as a parameter to the router. Router.js
class Paths extends Component {
render() {
return (
<div>
<Routes>
<Route
exact
path="/pallete/:name"
element={(match) => {
return <Pallete id={match} />;
}}
/>
<Route exact path="/" element={<Home />} />
</Routes>
</div>
);
} }
Pallete.js
class Pallete extends Component {
constructor(props) {
super(props);
this.state = {
contrast: 100,
copyValue: "",
id: this.props,
};
console.log(this.state.id);
}
}
Output:
{id: 'flat-ui-colors-american'}
react-router, or are you rather usingreact-router-domorreact-router-native? Or something else entirely?